GraphDiff causing id of entity to not get populated after saveChanges()

521 views Asked by At

When using graphDiff for creating a record the new id isn't getting populated back into the entity after saveChanges() is called. Its been logged on the github repo here - https://github.com/refactorthis/GraphDiff/issues/144 but the repo doesn't seem to be that active any more so was hoping someone on here would have some insight on how to get this working.

How it should work however qualification.Id is always 0 for a create. For an update it's the correct Id.

    public int CreateUpdate(Qualification qualification)
    {
        using (var db = new DataContext())
        {
            db.UpdateGraph(qualification);

            db.SaveChanges();

            return qualification.Id;
        }
    }

My current work around is to not use graph diff for creates but this isn't ideal.

    public int CreateUpdate(Qualification qualification)
    {
        using (var db = new DataContext())
        {
            if (qualification.Id == 0)
            {
                db.Entry(qualification).State = EntityState.Added;
            }
            else
            {
                db.UpdateGraph(qualification);
            }

            db.SaveChanges();

            return qualification.Id;
        }
    }

Thanks

1

There are 1 answers

0
Michael Esteves On

So I found the solution - https://github.com/refactorthis/GraphDiff/issues/32#issuecomment-34420859

Importantly "GraphDiff hands you a new instance back" so you need to set the return to your entity.

    public int CreateUpdate(Qualification qualification)
    {
        using (var db = new DataContext())
        {
            qualification = db.UpdateGraph(qualification);
            db.SaveChanges(qualification.AuditUserId);

            return qualification.Id;
        }
    }