我有一个父类
public class Parent
{
public Parent(DateTime? date) { Date = date; }
public DateTime? Date { get; set; }
public List<Child> Children { get; set; }
public void Save()
{
foreach(var child in Children)
{
child.Save(Date ?? DateTime.Now);
}
}
}
显然,我也有一个子班,我的问题的真正原因是:
public class Child
{
public Child () {}
public Decision FirstDecision { get; set;}
public Decision SecondDecision { get; set; }
public OtherProperty SomeOtherProperty { get; set; }
public void Save(DateTime date)
{
SaveFirstDecision(date);
SaveSecondDecision(date);
}
public void SaveFirstDecision(date)
{
var type = FactoryTools.Factory.CreateQueryable<DecisionType>()
.FirstOrDefault(x => x.Name = "First");
if(FirstDecision == null) FirstDecision = new Decision { Type = type };
FirstDecision.SomeOtherPropery = SomeOtherProperty;
FirstDecision.SomeDate = date;
FactoryTools.Factory.SaveOrUpdate(FirstDecision);
}
public void SaveSecondDecision(date)
{
var type = FactoryTools.Factory.CreateQueryable<DecisionType>()
.FirstOrDefault(x => x.Name = "Second");
if(SecondDecision == null) SecondDecision = new Decision { Type = type };
SecondDecision.SomeOtherPropery = SomeOtherProperty;
SecondDecision.SomeDate = date;
// This is where the Exception occurs
FactoryTools.Factory.SaveOrUpdate(SecondDecision);
}
}
所以在第二次 SaveOrUpdate 中,NHibernate 抛出这个异常:
Cannot insert duplicate key row in object 'dbo.d_decision' with unique index 'd_decision_i1'.
我不明白为什么 NHibernate 将这两个决定视为重复...我尝试了很多事情,包括覆盖Equals
andHashCode
但似乎无法避免这个问题。谢谢你的帮助。
顺便说一句,这里显示的类只是我认为是相关代码片段的抽象,这些类中还有其他属性,但我不认为它们是相关的......