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?
IEnumerable<T>does not have anAddmethod and yourSavemethod would not compile because of this and because you don't return aUser. I guess, this is not your "real" code, is it? - SlaumaICollections, which I fixed in my snippet. Btw, the linepocoObject.Companies.Last()is a POCO object, and not a tracked entity. - NexxaspocoObject.Companies.Last()is a new company, not yet existing in the DB, right?) and create a relationship between the existing user and this new company, right? - Slauma_dbContext2in yourSavemethod and replace the two_dbContextin your code by_dbContext2. Execute in debugger and watch the database tables directly after_dbContext2.SaveChanges(). If this should work (no user duplication) then you know at least that something else happens with your_dbContextinstance which causes the duplication. - Slauma