NHibernate - 无法保存子实体 [英] NHibernate - Unable to save child entities
问题描述
这应该是一个简单的 1-N 关系,但是我无法保存孩子,因为 NHibernate 在孩子的插入语句中使用 null 作为值.
This is supposed to be a simple 1-N relationship, however I am not able to save the children as NHibernate uses null as a value in the insert statement of the child.
public class Event
{
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<EventParameter> Parameters{ get; set; }
public Event() { Parameters = new List<EventParameter>(); }
}
[Serializable]
public class EventParameter : Parameter
{
public virtual Event Event { get; set; }
public virtual string ComparisonMethod { get; set; }
public override bool Equals(object obj) {}
public override int GetHashCode() {}
}
映射是这样的
public EventMapping()
{
Table(...);
Id(x => x.Id)
.Column(...)
.GeneratedBy
.Custom<global::NHibernate.Id.SequenceGenerator>(builder => builder.AddParam("sequence", "..."));
Map(x => x.Name).Column("Name").Length(100);
HasMany<EventParameter>(x => x.Parameters)
.KeyColumns.Add(...)
.Inverse()
.Cascade.All();
}
public EventParameterMapping()
{
Table(....);
CompositeId()
.KeyProperty(x => x.Event.Id, "...")
.KeyProperty(x => x.ParameterId, "...");
References(x => x.Event);
}
父级的 Insert 语句是正确的,但对于子级则不是.
The Insert statement for the parent is correct, however for the child it is not.
INSERT INTO ...
(...columns...)
VALUES (..., null, ...)
在此发生之前,我收到以下警告:无法确定实体是暂时的还是分离的;查询数据库.在会话中使用显式 Save() 或 Update() 来防止这种情况发生.
Before this happens I get the following warning: Unable to determine if entity is transient or detached; querying the database. Use explicit Save() or Update() in session to prevent this.
我确实在交易中使用了 Save().知道为什么会发生这种情况吗?
I do use Save() in the transaction. Any ideas why this happens?
推荐答案
这里的解决方案出人意料地简单.我们必须使用 inverse="true"
映射:
Solution here is suprisingly simply. We have to use inverse="true"
mapping:
HasMany<EventParameter>(x => x.Children)
.KeyColumns.Add("...")
.Inverse()
.Cascade.All();
但是,这是一种优化,需要在我们的 C# 代码中始终正确设置关系的双方:
But, this is kind of optimization, which would require both sides of relation to be always properly set in our C# code:
var parent = ...;
var child = new Child();
// both sides MUST be set
parent.Children.Add(child);
child.Parent = parent;
请注意查看更多详情
这篇关于NHibernate - 无法保存子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!