2010-08-16 54 views
6

我开始一个简单的.NET项目与FluentNhibernate
我跟着我在互联网上找到的几个例子,它似乎很容易掌握。
我意识到如果让FluentNhibernate构建我的数据库模式(Sql Server 2000),它会为我的字符串模型属性生成NVARCHAR字段。FluentNHibernate和VARCHAR列

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

这段代码的伟大工程:

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); 
    } 
} 

现在,我的客户表的所有字段是VARCHAR,但地址的组件仍然作为创建的字段(街道,城市和邮编) NVARCHAR。

+0

显然有在流利,NHibernate的错误:-s – LeftyX 2010-08-25 16:54:18

回答

11

找到定义AnsiStringCustomType的解决方案:

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); 
    } 
}