我有一个父类
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
但似乎无法避免这个问题。谢谢你的帮助。
顺便说一下,这里显示的类只是我认为相关代码片段的抽象,这些类中还有其他属性,但我不相信它们是相关的......
答案 0 :(得分:1)
正如Darren Kopp所指出的,这是数据库的一个问题。我们的一个dba在该表上创建了一个索引,要求在某些列的组合中,至少有一个必须是不同的...