0
時,我有一個父類NHibernate的認爲我有一個重複的對象使用SaveOrUpdate
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
和HashCode
,但似乎無法避免此問題。謝謝你的幫助。
順便說一句,這裏顯示的類,但什麼,我認爲是的代碼中的相關作品抽象,有這些類的其他屬性,但我不相信他們是相關...
這不是nhibernate看到重複,這是數據庫看到重複。你的id生成器設置爲什麼? – 2013-04-11 18:11:07
'Id'列是'主鍵','標識:是','增量:1','種子:1'映射爲:'Id(x => x.Id,map => {map.Column (「id」); map.Generator(Generators.Identity);});' – 2013-04-11 18:33:10