Retrieving / updating Entity Framework POCO objects that already exist in the ObjectContext

I have a project using Entity Framework 4.0 with POCOs (data is stored in SQL DB, lazyloading is enabled) as follows:

public class ParentObject { public int ID {get; set;} public virtual List<ChildObject> children {get; set;} } public class ChildObject { public int ID {get; set;} public int ChildRoleID {get; set;} public int ParentID {get; set;} public virtual ParentObject Parent {get; set;} public virtual ChildRoleObject ChildRole {get; set;} } public class ChildRoleObject { public int ID {get; set;} public string Name {get; set;} public virtual List<ChildObject> children {get; set;} } 

I want to create a new ChildObject, assign a role to it, and then add it to an existing ParentObject. Subsequently, I want to send a new ChildObject to the caller.

The code below works fine until it tries to return an object from the database. NewChildObjectInstance has only a ChildRoleID set and does not contain a reference to the actual ChildRole object. I am trying to pull a new instance from a database to populate the ChildRole property. Unfortunately, in this case, instead of creating a new ChildObject instance and assigning it to retreivedChildObject, EF finds the existing ChildObject in context and returns an in-memory instance with the ChildRole property set to zero.

 public ChildObject CreateNewChild(int id, int roleID) { SomeObjectContext myRepository = new SomeObjectContext(); ParentObject parentObjectInstance = myRepository.GetParentObject(id); ChildObject newChildObjectInstance = new ChildObject() { ParentObject = parentObjectInstance, ParentID = parentObjectInstance.ID, ChildRoleID = roleID }; parentObjectInstance.children.Add(newChildObjectInstance); myRepository.Save(); ChildObject retreivedChildObject = myRepository.GetChildObject(newChildObjectInstance.ID); string assignedRoleName = retreivedChildObject.ChildRole.Name; //Throws exception, ChildRole is null return retreivedChildObject; } 

I tried setting MergeOptions to Overwrite by calling ObjectContext.Refresh () and ObjectContext.DetectChanges () to no avail ... I suspect this is due to proxy objects that EF introduces when working with POCOs.

Has anyone encountered this problem before? If so, what was the solution?

+4
source share
1 answer

You should not use β€œnew” to create a new object, but use ObjectContext.CreateObject () . Thus, the proxy server of your object will be created instead of the POCO class.

I know this is an old question, but I stumbled upon it and just read about it a second ago.

+3
source

Source: https://habr.com/ru/post/1309810/


All Articles