I have two classes that I have simplified for this SO question. Whenever I add a new 'parent' and attach existing 'child' entities, I end up with duplicated children. What am I doing wrong?
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();
}
I hope I didn't make any errors when I simplified this code. Can anyone assist?
Parentyou meanGroup. And you get two newChildrecords created?new RPSContext?