I am using Entity Framework Code first my classes are
[Serializable]
public class Emp
{
public int EmpId { get; set; }
public byte TitleId { get; set; }
[MaxLength(50)]
public string FirstName { get; set; }
[MaxLength(50)]
public string Surname { get; set; }
public byte Type { get; set; }
public List<PracticeEmp> PracticeEmps { get; set; }
}
[Serializable]
public class PracticeEmp
{
public int PracticeStaffId { get; set; }
public int PracticeId { get; set; }
public int EmpId { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public Emp Emp { get; set; }
}
when I am trying to insert data into PracticeEmps table for a staff which already exists I use the following code
Db.Current.Emps.Attach(practiceEmp.Emp);
Db.Current.PracticeEmps.Add(practiceEmp);
This code segment returns an error on attach method “An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.”
any Ideas…
practiceEmp instance will be automatically attached to your context if the Emp instance you are attaching has a reference to it and it is not part of the context already. Note that both entities will be in Unchanged state which is the default state for attached entities.