Guest User

Untitled

a guest
Aug 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. How do you add new child entities to a parent in EF4?
  2. // Objects created by POCO template generator
  3. public class User
  4. {
  5. public int Id { get; set; }
  6. public string Username { get; set; }
  7. public ICollection<Company> Companies { get; set; }
  8. }
  9. public class Company
  10. {
  11. public int Id { get; set; }
  12. public string Name { get; set; }
  13. public ICollection<User> Users { get; set; }
  14. }
  15.  
  16. public UserRepository
  17. {
  18. internal ObjectContextEntities _dbContext = new ObjectContextEntities();
  19. public User Save(User pocoObject)
  20. {
  21. // Load the existing User which has no companies
  22. var loadedEntity = _dbContext.Users.Where(m => m.Id == pocoObject.Id).FirstOrDefault();
  23.  
  24. // Add the new company from a POCO object
  25. loadedEntity.Companies.Add(pocoObject.Companies.Last());
  26.  
  27. _dbContext.SaveChanges();
  28. }
  29. }
  30.  
  31. public class User
  32. {
  33. public int Id { get; set; }
  34. public string Username { get; set; }
  35. public ICollection<Company> Companies { get; set; }
  36.  
  37. public User()
  38. {
  39. Companies = new List<Company>();
  40. }
  41. }
  42.  
  43. public class Company
  44. {
  45. public int Id { get; set; }
  46. public string Name { get; set; }
  47. }
  48.  
  49. public class POCOEntitiesContext : ObjectContext
  50. {
  51. private ObjectSet<User> users;
  52. public ObjectSet<User> Users
  53. {
  54. get { return users; }
  55. }
  56.  
  57. private ObjectSet<Company> companies;
  58. public ObjectSet<Company> Companies
  59. {
  60. get { return companies; }
  61. }
  62.  
  63. public POCOEntitiesContext() : base("name=POCOEntities", "POCOEntitiesContainer")
  64. {
  65. users = CreateObjectSet<User>();
  66. companies = CreateObjectSet<Company>();
  67. }
  68. }
  69.  
  70. using (var ctx = new POCOEntitiesContext())
  71. {
  72. var loadedUser = ctx.Users.Where(u => u.Username == "Peri").First();
  73. loadedUser.Companies.Add(new Company() { Name = "New Company" });
  74. ctx.SaveChanges();
  75. }
  76.  
  77. var newCompany = pocoObject.Companies.Last();
  78. newCompany.Users = null;
  79. loadedUser.Companies.Add(newCompany);
  80.  
  81. loadedUser.Companies.Add(new Company() { Name = "New Company" });
Add Comment
Please, Sign In to add comment