Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Updating object in Entity Framework 4 - A relationship from the AssociationSet is in the 'Added' state
- using (tamcEntities myObjectContext = new tamcEntities())
- {
- // Attach all related objects to context
- List<FIPS> fipsList = new List<FIPS>();
- foreach (FIPS fips in myUser.FIPS)
- {
- FIPS myFIPS = new FIPS { FIPS_Code = fips.FIPS_Code };
- myObjectContext.FIPSCodes.Attach(myFIPS);
- fipsList.Add(myFIPS);
- }
- List<Region> regionsList = new List<Region>();
- foreach (Region region in myUser.Regions)
- {
- Region myRegion = new Region { RegionID = region.RegionID };
- myObjectContext.Regions.Attach(myRegion);
- regionsList.Add(myRegion);
- }
- Role myRole = new Role { ID = myUser.Role.ID };
- myObjectContext.Roles.Attach(myRole);
- // Remove existing relationship in user entity
- //myUser.Role = null;
- myUser.FIPS.Clear();
- myUser.Regions.Clear();
- // Assign related objects to user entity
- foreach (FIPS fipsCode in fipsList)
- {
- myUser.FIPS.Add(fipsCode);
- }
- foreach (Region region in regionsList)
- {
- myUser.Regions.Add(region);
- }
- myUser.Role = myRole;
- if (myUser.ID == 0)
- {
- myObjectContext.Users.AddObject(myUser);
- }
- else
- {
- myObjectContext.ObjectStateManager.ChangeObjectState(myUser, System.Data.EntityState.Modified);
- }
- result = (myObjectContext.SaveChanges(SaveOptions.None) != 0);
- }
Advertisement
Add Comment
Please, Sign In to add comment