I have two simple DB Tables:
Persons (id, name, house)
Houses (id, street, city)
The 'house' column of the Persons table is the foreign key to specify in which house a person lives. Easy example. I created a model from the Database and now I am trying to learn how to work with the EF. I am for instance trying to attach a disconnected entity to an existing context:
House dh = new House() { city = "Seattle", street = "St Road 1" };
dh.Persons = new List<Person>();
dh.Persons.Add(new Person { namen = "Andrew" });
dh.Persons.Add(new Person { namen = "Thorsten" });
YardEntities cx = new YardEntities();
cx.Houses.Attach(dh);
The last line throws an Exception I do not understand:
Additional information: Attaching an entity of type 'DataAccessLayer.Person' failed because another entity of the same type already has the same primary key value.
Why is that? Andy ideas? The primary key 'id' has an auto increment and is the primary key of my tables.
Edit:
Code of my two entity classes:
public partial class Person
{
public int id { get; set; }
public string namen { get; set; }
public int house { get; set; }
public virtual House House1 { get; set; }
}
public partial class House
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public House()
{
this.Persons = new HashSet<Person>();
}
public int id { get; set; }
public string street { get; set; }
public string city { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Person> Persons { get; set; }
}