Why is my Entity Framework Code First proxy collection null and why can't I set it?

后端 未结 3 865
误落风尘
误落风尘 2020-12-01 01:38

I am using DBContext and have two classes whose properties are all virtual. I can see in the debugger that I am getting a proxy object when I query the context. However, a c

3条回答
  •  感情败类
    2020-12-01 02:09

    As you correctly observed in the answer to your own question, removing the "virtual" keyword from the collection properties works around the problem, by preventing the Entity Framework from creating a change tracking proxy. However, this is not a solution for many people, because change tracking proxies can be really convenient and can help prevent issues when you forget to detect changes at the right places in your code.

    A better approach would be to modify your POCO classes, so that they instantiate the collection properties in their get accessor, rather than in the constructor. Here's your POCO class, modified to allow change tracking proxy creation:

    public class DanceEvent
    {
        private ICollection _danceStyles;
        public virtual ICollection DanceStyles
        {
            get { return _danceStyles ?? (_danceStyles = new Collection()); }
            protected set { _danceStyles = value; }
        }
    }
    

    In the above code the collection property is no longer automatic, but rather has a backing field. It's better if you leave the setter protected, preventing any code (other than the proxy) from subsequently modifying these properties. You will notice that the constructor was no longer necessary and was removed.

提交回复
热议问题