我有以下枚举类型:
public enum EnumType { E1, E2 }
用于以下类:
public class X { public virtual int? Id { get; set; } public virtual EnumType EnumProperty { get; set; } public virtual string S { get; set; } }
我想使用NHibernate在数据库中保留此类实例.为避免编写样板代码,我试图使用自动映射功能,如下所示:
private ISessionFactory CreateSessionFactory() { var mappings = AutoMap .AssemblyOf(new MyAutoMappingConfiguration()); this.NHibernateConfiguration = Fluently .Configure() .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2012.ConnectionString( b => b.FromConnectionStringWithKey("x"))) .Mappings(m => m.AutoMappings.Add(mappings)) .BuildConfiguration(); return this.NHibernateConfiguration.BuildSessionFactory(); }
这里MyAutoMappingConfiguration
看起来是这样的:
public class MyAutoMappingConfiguration: FluentNHibernate.Automapping.DefaultAutomappingConfiguration { public override bool ShouldMap(Type type) { return type.Namespace == "Domain"; } public override bool IsComponent(Type type) { return type.Name == "EnumType"; } }
当我使用从此配置生成的模式来创建数据库时:
new SchemaExport(this.sessionProvider.NHibernateConfiguration) .Execute(true, true, false);
正在生成并执行以下脚本:
if exists (select * from dbo.sysobjects where id = object_id(N'[X]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [X]
create table [X] (
Id INT not null,
S NVARCHAR(255) null,
primary key (Id)
)
为什么财产EnumProperty
被忽略了?
当我X
为这样的自动映射添加显式映射,或者(看似等效的)覆盖:
var mappings = AutoMap .AssemblyOf(new MyAutoMappingConfiguration()) .Override (m => { m.Table("X"); m.Id(x => x.Id); m.Map(x => x.EnumProperty); // this works m.Map(x => x.S); });
脚本生成正确:
if exists (select * from dbo.sysobjects where id = object_id(N'[X]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [X]
create table [X] (
Id INT not null,
EnumProperty NVARCHAR(255) null,
S NVARCHAR(255) null,
primary key (Id)
)
这表明NHibernate正确映射所呈现的枚举的能力似乎没有任何问题.为什么无法自动映射应对此问题?
当我将以下方法添加到MyAutoMappingConfiguration
:
public override bool ShouldMap(Member member) { var result = base.ShouldMap(member); return result; }
并把断点时,result
就是true
为EnumProperty
会员,这在某种程度上被忽略后面.