How do I get fluent nhibernate to create a varbinary(max) field in sql server

后端 未结 6 573
臣服心动
臣服心动 2020-12-06 17:00

How can I get fluent nhibernate to create a varbinary field in a sql server 2005 table that uses a field size of varbinary(max)? At the moment I always get a default of varb

6条回答
  •  一向
    一向 (楼主)
    2020-12-06 17:38

    AFAIK, there is no such thing in Fluent NHibernate as "max", however, if you set the allowed length of a column to a real big value, it should work fine. You can check MSDN for what number max means for each datatype in SQL Server, although it may mean some very different number in others.

    I used reflector and found this:

    public MsSql2005Dialect()
    {
        base.RegisterColumnType(DbType.String, 0x3fffffff, "NVARCHAR(MAX)");
        base.RegisterColumnType(DbType.AnsiString, 0x7fffffff, "VARCHAR(MAX)");
        base.RegisterColumnType(DbType.Binary, 0x7fffffff, "VARBINARY(MAX)");
    }
    

    So, it seems that NHibernate creates max by default? Still, Fluent doesn't. (Although I don't know why.)

    With the Auto mapping feature, you can use conventions to achieve it.

    Example:

    var cfg = new Configuration();
    
    var persistenceModel = new AutoPersistenceModel();
    persistenceModel.Conventions.Add(
        new PropertyConvention(),
        new ReferenceConvention(),
        new HasManyConvention(),
        ConventionBuilder.Property.Always(delegate(IPropertyInstance instance)
        {
            if (instance.Property.PropertyType == typeof(string))
                instance.Length(16000);
            else if (instance.Property.PropertyType == typeof(byte[]))
                instance.Length(30000000);
        }));
    persistenceModel.AddTypeSource(new AssemblyTypeSource(Assembly.GetExecutingAssembly()));
    persistenceModel.Where(t => t.Namespace.EndsWith("Entities"));
    
    cfg.AddAutoMappings(persistenceModel);
    return cfg.BuildSessionFactory();
    

    For me, this suffices, but you can always use larger numbers.

    If you don't use automapping, Dan Fitch's solution is the way to go, I guess.

提交回复
热议问题