【发布时间】:2018-01-13 03:00:02
【问题描述】:
我正在尝试建立如下关系。每个Master项都有一个或多个Detail项:
public class Detail {
public virtual Guid DetailId { get; set; }
public virtual string Name { get; set; }
}
public class Master {
public virtual Guid MasterId { get; set; }
public virtual string Name { get; set; }
public virtual IList<Detail> Details { get; set; }
}
和映射:
public class MasterMap : ClassMap<Master>
{
public MasterMap()
{
Id(x => x.MasterId);
Map(x => x.Name);
HasMany(x => x.Details).Not.KeyNullable.Cascade.All();
}
}
public class DetailMap : ClassMap<Detail>
{
public DetailMap()
{
Id(x => x.Id);
Map(x => x.Name);
}
}
Master数据库表是:
masterId uniqueidentifier NOT NULL
name nvarchar(max) NULL
而详情是:
DetailId uniqueidentifier NOT NULL
name nvarchar(max) NULL
MasterId uniqueidentifier NULL
foreign key (masterId) references [Master]
我并不真正关心从 Detail 到 Master 的链接——换句话说,Detail 对象本身对我的域层不感兴趣。它们将始终通过它们的 Master 对象进行访问。
使用这样的代码:
Master mast = new Master
{
MasterId = new Guid(),
Name = "test",
Details = new List<Detail>
{
new Detail { .DetailId = new Guid(), .Name = "Test1" },
new Detail { .DetailId = new Guid(), .Name = "Test1" }
}
};
using (transaction == Session.BeginTransaction)
{
Session.Save(mast);
transaction.Commit();
}
这很好用,除了this post 中概述的一个疯狂限制:NHibernate 执行 INSERT 并将 Detail.MasterId 首先设置为 NULL,然后执行 UPDATE 将其设置为真正的 MasterId。
真的,我不想要 NULL MasterIds 的 Detail 条目,所以如果我将 MasterId 字段设置为 NOT NULL,INSERT 到 Detail 将失败,因为正如我所说 NHibernate 试图放入 MasterId = NULL。
我想我的问题归结为:
如何使上述代码示例与我现有的域模型一起使用(例如,不添加 Detail.Master 属性),并且数据库中的 Detail.MasterId 字段设置为 NOT NULL?
有没有办法让 Nhibernate 将正确的 MasterId 放在初始 INSERT 中,而不是之后运行 UPDATE?这个设计决定是否有理由? -- 我很难理解为什么会这样。
【问题讨论】:
标签: nhibernate fluent-nhibernate one-to-many