I am working with VS2010, .NET 4.0, Entity Framework 4, and POCO entities. I am trying to add and remove child entities from a parent. I have a many-to-many relationship between [User] and [Companies]. So I have the following entity:
// Objects created by POCO template generator
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public ICollection<Company> Companies { get; set; }
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<User> Users { get; set; }
}
At this point in the code, the User exists but has ZERO companies. What I am trying to do is add a new child Company to the User. This code DOES save the Company but it is also creating a duplicate User parent.
public UserRepository
{
internal ObjectContextEntities _dbContext = new ObjectContextEntities();
public User Save(User pocoObject)
{
// Load the existing User which has no companies
var loadedEntity = _dbContext.Users.Where(m => m.Id == pocoObject.Id).FirstOrDefault();
// Add the new company from a POCO object
loadedEntity.Companies.Add(pocoObject.Companies.Last());
_dbContext.SaveChanges();
}
}
How should I be adding child entities? (Without creating a duplicate relationship?) … Also is there a simple way to update those children when performing “ApplyCurrentValues()” on the parent User?
I tried a more simplified approach and I figured it out:
It turns out because there was a reference to the parent INSIDE the child, it was propagating up and causing a new parent to be created. So from a POCO standpoint, I had to remove the parent and keep it a very simple object. (Or I could have just removed the Child’s Parent reference in the edmx). But even this makes my life easier: