Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- How do you add new child entities to a parent in EF4?
- // 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; }
- }
- 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();
- }
- }
- public class User
- {
- public int Id { get; set; }
- public string Username { get; set; }
- public ICollection<Company> Companies { get; set; }
- public User()
- {
- Companies = new List<Company>();
- }
- }
- public class Company
- {
- public int Id { get; set; }
- public string Name { get; set; }
- }
- public class POCOEntitiesContext : ObjectContext
- {
- private ObjectSet<User> users;
- public ObjectSet<User> Users
- {
- get { return users; }
- }
- private ObjectSet<Company> companies;
- public ObjectSet<Company> Companies
- {
- get { return companies; }
- }
- public POCOEntitiesContext() : base("name=POCOEntities", "POCOEntitiesContainer")
- {
- users = CreateObjectSet<User>();
- companies = CreateObjectSet<Company>();
- }
- }
- using (var ctx = new POCOEntitiesContext())
- {
- var loadedUser = ctx.Users.Where(u => u.Username == "Peri").First();
- loadedUser.Companies.Add(new Company() { Name = "New Company" });
- ctx.SaveChanges();
- }
- var newCompany = pocoObject.Companies.Last();
- newCompany.Users = null;
- loadedUser.Companies.Add(newCompany);
- loadedUser.Companies.Add(new Company() { Name = "New Company" });
Add Comment
Please, Sign In to add comment