Serj Sagan
Serj Sagan

Reputation: 30208

NHibernate thinks I have a duplicate object when using SaveOrUpdate

I have a parent class

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);
        }
    }
}

Obviously, I also have a child class, and the the real cause for my issue:

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);
    }
}

So on the second SaveOrUpdate, NHibernate throws this exception: Cannot insert duplicate key row in object 'dbo.d_decision' with unique index 'd_decision_i1'.

I do not understand why NHibernate sees these two decisions as duplicates... I have tried many things, including overriding the Equals and HashCode but can not seem to avoid this issue. Thanks for your help.

Btw, the classes shown here are but abstractions of what I believe to be the relevant pieces of code, there are other properties in these classes, but I do not believe they are relevant...

Upvotes: 0

Views: 1217

Answers (1)

Serj Sagan
Serj Sagan

Reputation: 30208

As was pointed out by Darren Kopp, this was an issue with the database. One of our dba's created an Index on that table that required that in a certain combination of columns, at least one had to be different...

Upvotes: 1

Related Questions