EF代码首先始终插入新的子记录,而不是将其与1:1关系

时间:2016-08-02 03:19:23

标签: c# entity-framework

我有这些课程

public class Subdist
{
    public int ID { get; set; }
    public virtual ICollection<SubdistPIC> SubdistPICs { get; set; }
}

public class SubdistPIC
{
    public int ID { get; set; }
    public Subdist Subdist { get; set; }
    public virtual PIC PIC { get; set; }
}

public class PIC
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
}

当我调用此方法时

    public void InsertSubdist(Subdist obj)
    {
        _uow.Subdist.Add(obj);
        _uow.Context.SaveChanges();
    }

它将自动插入新的PIC,而不是仅仅以1:1的关系链接它。例如:

如果我的PIC表有这些记录

PIC
ID  Name    Active
1   Tommy   1
2   Joel    1
3   Ellie   1

它现在有

PIC
ID  Name    Active
1   Tommy   1
2   Joel    1
3   Ellie   1
4   Tommy   1
5   Joel    1
6   Ellie   1

SubdistPIC
ID  PIC_ID Subdist_ID
1   5      1
2   4      1
3   6      1

我想要的是:

PIC
ID  Name    Active
1   Tommy   1
2   Joel    1
3   Ellie   1

SubdistPIC
ID  PIC_ID Subdist_ID
1   1      1
2   2      1
3   3      1

知道怎么做到这一点?我是EF的新手

0 个答案:

没有答案