我试图在整个地方搜索有关这方面的信息,但似乎没有人能够完全解决这个问题。我把它简化为下面的例子。
这是我的数据库:
create table ThingTypes
(
Id int,
Name varchar(50) not null
constraint PK_ThingTypes primary key (Id)
)
go
insert into ThingTypes(Id, Name) Values(1, 'ThingTypeOne')
insert into ThingTypes(Id, Name) Values(2, 'ThingTypeTwo')
create table Things
(
Id int identity,
Name varchar(50) not null,
ThingTypeId int not null
constraint PK_Things primary key (Id),
constraint FK_Things_ThingTypes foreign key (ThingTypeId) references ThingTypes(Id)
)
go
这是我的模特:
public abstract class Thing
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class ThingTypeOne : Thing { }
public class ThingTypeTwo : Thing { }
这些是我的映射:
public class ThingOverride : IAutoMappingOverride<Thing>
{
public void Override(AutoMapping<Thing> mapping)
{
mapping.DiscriminateSubClassesOnColumn("ThingTypeId", 0);
}
}
public class ThingTypeOneMap : SubclassMap<ThingTypeOne>
{
public ThingTypeOneMap()
{
DiscriminatorValue(1);
}
}
public class ThingTypeTwoMap : SubclassMap<ThingTypeTwo>
{
public ThingTypeTwoMap()
{
DiscriminatorValue(2);
}
}
这是我的ISessionFactory构建器:
public static ISessionFactory GetFactory(string connectionString)
{
var configuration = new Configuration().AddProperties(new Dictionary<string, string>
{
{Environment.ConnectionDriver, typeof (SqlClientDriver).FullName},
{Environment.Dialect, typeof (MsSql2008Dialect).FullName},
{Environment.ConnectionProvider, typeof (DriverConnectionProvider).FullName},
{Environment.ConnectionString, connectionString},
{Environment.ShowSql, "true"},
{Environment.BatchSize, "100"},
{Environment.Isolation, "ReadCommitted"}
});
return Fluently.Configure(configuration)
.Mappings(m =>
{
m.FluentMappings.AddFromAssemblyOf<ThingTypeOneMap>();
m.AutoMappings.Add(AutoMap.AssemblyOf<Thing>(new DefaultAutomappingConfiguration())
.UseOverridesFromAssemblyOf<ThingOverride>()
);
})
.BuildSessionFactory();
}
这是我失败的测试:
var sessionFactory = SessionFactoryBuilder.GetFactory(@"Data Source=localhost;Initial Catalog=ThingDatabase;Trusted_Connection=True;");
using (var session = sessionFactory.OpenSession())
{
session.BeginTransaction();
session.SaveOrUpdate(new ThingTypeOne
{
Name = "New Thing Type One"
});
session.Transaction.Commit();
}
它失败了,因为它试图插入表“ThingTypeOne”,这显然不存在。我需要做些什么才能让Fluent NHibernate真正关注我设置的DiscriminateSubClassesOnColumn属性?
答案 0 :(得分:1)
而不是每个子类的子类映射添加约定
class DiscriminatorValueConvention : ISubclassConvention
{
public void Apply(ISubclassInstance instance)
{
if (instance.Type == typeof(ThingTypeOne))
{
instance.DiscriminatorValue(1);
}
else if (instance.Type == typeof(ThingTypeTwo))
{
instance.DiscriminatorValue(2);
}
}
}