Guest User

Untitled

a guest
May 9th, 2012
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. Updating object in Entity Framework 4 - A relationship from the AssociationSet is in the 'Added' state
  2. using (tamcEntities myObjectContext = new tamcEntities())
  3. {
  4.  
  5. // Attach all related objects to context
  6. List<FIPS> fipsList = new List<FIPS>();
  7. foreach (FIPS fips in myUser.FIPS)
  8. {
  9. FIPS myFIPS = new FIPS { FIPS_Code = fips.FIPS_Code };
  10. myObjectContext.FIPSCodes.Attach(myFIPS);
  11. fipsList.Add(myFIPS);
  12. }
  13.  
  14. List<Region> regionsList = new List<Region>();
  15. foreach (Region region in myUser.Regions)
  16. {
  17. Region myRegion = new Region { RegionID = region.RegionID };
  18. myObjectContext.Regions.Attach(myRegion);
  19. regionsList.Add(myRegion);
  20. }
  21.  
  22. Role myRole = new Role { ID = myUser.Role.ID };
  23. myObjectContext.Roles.Attach(myRole);
  24.  
  25. // Remove existing relationship in user entity
  26. //myUser.Role = null;
  27. myUser.FIPS.Clear();
  28. myUser.Regions.Clear();
  29.  
  30. // Assign related objects to user entity
  31. foreach (FIPS fipsCode in fipsList)
  32. {
  33. myUser.FIPS.Add(fipsCode);
  34.  
  35. }
  36.  
  37. foreach (Region region in regionsList)
  38. {
  39. myUser.Regions.Add(region);
  40.  
  41. }
  42.  
  43. myUser.Role = myRole;
  44.  
  45.  
  46. if (myUser.ID == 0)
  47. {
  48. myObjectContext.Users.AddObject(myUser);
  49. }
  50. else
  51. {
  52. myObjectContext.ObjectStateManager.ChangeObjectState(myUser, System.Data.EntityState.Modified);
  53. }
  54.  
  55. result = (myObjectContext.SaveChanges(SaveOptions.None) != 0);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment