I am pretty sure, the answer to this question should be easy, but I cannot find the answer after hours of googling...
- I do use Entity Framework and have two kind of objects, lets say one Street and several houses. The relationship is clear. One Street contains one or more houses.
This objects in EF looks like the following:
ctx.street.houses
etc.
If I use
ctx.street.houses.Add(newhouse)
I end up with a new house object in a database. Fine.
But how can I add an already given "house" object into the street? I always get a new house object and cannot get it to work to use my already created objects.
I found the Attach() function instead of the Add() function for the collection, but the
ctx.street.houses.Attach()
Function doesn`t exist in my environment, so this isn`t a solution at all.
Any one who can clear this up?
[EDIT]
public partial class DBEntity: DbContext
{
public DBEntity()
: base("name=DBEntity1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<client> Clients { get; set; }
public virtual DbSet<contactperson> ContactPersons { get; set;}
}
The Clients class:
public partial class Client
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Client()
{
this.ContactPersons = new HashSet<contactperson>();
}
public int Id { get; set; }
public string Company { get; set; }
public System.DateTime Date_Creation { get; set; }
public bool Active { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<contactperson> ContactPersons { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
and the ContactPerson class:
public partial class ContactPerson
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ContactPerson()
{
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public System.DateTime Date_Creation { get; set; }
public bool Active { get; set; }
public string EMail { get; set; }
public string Phone_Office { get; set; }
public string Phone_Mobile { get; set; }
public virtual Client Client { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
[/EDIT by Maciej Los (content moved from comment/answer]