FluentNHibernate和VARCHAR列

时间:2010-08-16 11:59:03

标签: nhibernate fluent-nhibernate conventions nvarchar

我正在使用 FluentNhibernate 启动一个简单的.NET项目 我已经在互联网上找到了几个我发现的例子,看起来很容易掌握 我意识到如果我让FluentNhibernate构建我的数据库模式(Sql Server 2000),它会为我的字符串模型属性生成 NVARCHAR 字段。

有人建议我可以添加一个约定来更改类型。

这段代码效果很好:

public class AnsiStringConvention : IPropertyConvention 
        {
            private static Type stringType = typeof(string);
            public void Apply(FluentNHibernate.Conventions.Instances.IPropertyInstance instance)
            {
                if (instance.Property.PropertyType == stringType)
                {
                    instance.CustomType("AnsiString");
                }
            }
        }

现在我的数据库字段是VARCHAR,正如我预期的那样 我需要在我的类中添加一个组件,遵循我放置地址的DDD模式 在一个单独的类中,并将其添加到我的Customer类 我为地址创建了一个单独的映射文件:

public class AddressMap : ComponentMap<Address>
{
    public AddressMap()
    {
        Map(x => x.Number);
        Map(x => x.Street)
            .Length(100);
        Map(x => x.City)
            .Length(50);
        Map(x => x.PostCode)
            .Length(5);
    }
}

现在,我的Customer表的所有字段都是VARCHAR,但Address(Street,City和PostCode)组件的字段仍然创建为NVARCHAR。

1 个答案:

答案 0 :(得分:11)

找到将AnsiString定义为CustomType的解决方案:

public class AddressMap : ComponentMap<Address>
{
    public AddressMap()
    {
        // this.Map(x => x.Number);
        this.Map(x => x.Street)
            .CustomType("AnsiString") 
            .Length(100);
        this.Map(x => x.City)
            .CustomType("AnsiString")
            .Length(30);
        this.Map(x => x.State)
            .CustomType("AnsiString")
            .Length(20);
        this.Map(x => x.PostalCode)
            .CustomType("AnsiString")
            .Length(10);
        this.Map(x => x.Country)
            .CustomType("AnsiString")
            .Length(40);
    }
}