保存父级时,嵌套的现有实体会重复

时间:2015-09-08 03:44:12

标签: c# entity-framework entity-framework-6

当我尝试保存一个嵌套了现有实体的新实体时,我遇到了问题。不是与现有实体建立关系,而是重复它们。

这大致是我的模特:

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

我不希望添加任何重复的AddressLineTypes,所以在我的代码中我正在做这样的事情:

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

我在db.SaveChanges()之前点击了一个断点,并填充了AddressLineType ID,但它在数据库中创建了新条目,就像ID == 0一样。

如何在保存时停止现有的AddressLineTypes重复?

1 个答案:

答案 0 :(得分:2)

尝试使用单个上下文:

$ python -m wand.version -v
Wand 0.4.1
ImageMagick 6.9.2-0 Q16 x86_64 2015-09-08 http://www.imagemagick.org