2

I am having a problem where when I try to save a new entity that has existing entities nested. Instead of creating a relationship with existing entities it is duplicating them.

This is roughly my model:

public class Record
{
    public int ID { get; set; }
    public string RecordValue { get; set; }
    public virtual ICollection<AddressLine> AddressLines { get; set; }
}
public class AddressLine
{
    public int ID { get; set; }
    public string AddressLineValue { get; set; }
    public virtual ICollection<AddressLineType> AddressLineTypes { get; set; }
}
public class AddressLineType
{
    public int ID { get; set; }
    public string AddressLineTypeValue { get; set; }
}

I don't want any duplicate AddressLineTypes added so in my code I am doing something like this:

public void button1_Click(object sender, EventArgs e)
{

    Record r = new Record();
    r.RecordValue = "Record value";

    AddressLine al = new AddressLine();
    al.AddressLineValue = "Address line value";

    AddressLineType alt;
    using (var db = new MyDbContext())
    {
        alt = db.AddressLineTypes.Single(x => x.Value == "TypeValue");
    }

    al.AddressLineTypes.Add(alt);
    r.AddressLines.Add(al);

    SaveRecord(r);
}

public void SaveRecord(Record r)
{
    using (var db = new MyDbContext())
    {
        db.Records.Add(r);
        db.SaveChanges();
    }
}

I have hit a breakpoint before db.SaveChanges() and the AddressLineType ID is populated but it creates new entries in the database as if ID == 0.

How do I stop the existing AddressLineTypes duplicating on save?

1 Answer 1

2

Try using a single Context:

...    
using (var db = new MyDbContext())
        {
            alt = db.AddressLineTypes.Single(x => x.Value == "TypeValue");


            al.AddressLineTypes.Add(alt);
            r.AddressLines.Add(al);

            SaveRecord(r, db);
        }
    }

public void SaveRecord(Record r, MyDbContext db)
{
        db.Records.Add(r);
        db.SaveChanges();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I'll see if I can get that to work. My logic is a bit strange as the data comes in by way of a listener so I am making a request then spinning a while loop checking a Dictionary index for the request token and grabbing the object from the value. I would have to move a lot of logic out of my listener to get that to work. I guess I need to refactor all the code, I was hoping for a quick way to make the nested entities save properly when detached from the context :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.