Does Entity Framework support circular references?

前端 未结 4 2087
感动是毒
感动是毒 2021-01-04 06:42

I have two entities in parent/child relationship. In addition, parent contains a reference to a \"main\" child, so the simplified model looks like this:

clas         


        
4条回答
  •  梦谈多话
    2021-01-04 07:02

    Both EF and LINQ to SQL have this problem of not being able to save circular references, even though they could be a lot more helpful by just encapsulating 2 or more SQL calls in a transaction behind the scenes for you instead of throwing an Exception.

    I wrote a fix for this in LINQ to SQL but haven't gotten around to doing so in EF yet, because I've just been avoiding circular references in my db design for the time being.

    What you can do is create a helper method that sets aside circular references, run that before calling SaveChanges(), run another method that puts the circular references back in place, and call SaveChanges() again. You can encapsulate all of that in a single method, maybe SaveChangesWithCircularReferences().

    To put the circular references back, you need to track what you removed and return that log.

    public class RemovedReference() . . .
    
    public List SetAsideReferences()
    {
        . . .
    }
    

    So basically the code in SetAsideReferences is hunting down circular references, setting aside one half in each case, and recording those in a list.

    In my case I created a class that stored the object, the property name, and the value (another object) that was removed, and just kept these in a list, like so:

    public class RemovedReference
    {
        public object Object;
        public string PropertyName;
        public object Value;
    }
    

    There's probably a smarter structure to accomplish this; you could use a PropertyInfo object for example instead of a string, and you might cache the type to cheapen the second round of reflection.

提交回复
热议问题