我有兩個類,我已經簡化了這個SO問題。每當我添加一個新的「父母」並附上現有的「孩子」實體時,我最終會得到重複的孩子。我究竟做錯了什麼?爲什麼我的實體框架對象重複?
public class Group
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int GroupId { get; set; }
public virtual Child ChildOne { get; set; }
public virtual Child ChildTwo { get; set; }
}
public class Child
{
[Key]
public int ChildId { get; set; }
public bool Available { get; set; }
}
using (var context = new RPSContext())
{
Child childOne = context.Child.Where(p => p.Available == true).OrderBy(p => p.ChildId).FirstOrDefault();
Child childTwo = context.Child.Where(p => p.Available == true).OrderBy(p => p.ChildId).Skip(1).Take(1).FirstOrDefault();
}
Parent parent = new Models.Parent;
parent.ChildOne = childOne;
parent.ChildTwo = childTwo;
using (var context = new RPSContext())
{
context.Parent.Add(parent);
parent.ChildOne.Available = false;
parent.ChildTwo.Available = false;
context.SaveChanges();
}
我希望當我簡化了這個代碼,我沒有做任何的錯誤。任何人都可以協助
我猜你的意思是「組」。你會得到兩個新的「兒童」記錄? –
是的,它確實是一對多的關係。父/子是錯誤的術語,但我確實得到了多個子對象。 –
我想知道是否有一些背景廢話在這裏進行。你可以重構這個,所以你只有一個'新的RPSContext'? – Vlad274