Code First adding to collections? How to use Code First with repositories?

前端 未结 6 1337
执笔经年
执笔经年 2020-12-17 14:58

EDIT: This happen only on larger scale projects with repositories. Is there anybody using EF4 with CodeFirst approach and using repositories? Please advise me.

Hi. I

6条回答
  •  清酒与你
    2020-12-17 15:42

    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 the original Author POCO class, modified to allow change tracking proxy creation:

    public class Author
    {
        public virtual int AuthorId { get; set; }
        public virtual string Name { get; set; }
    
        private ICollection _books;
    
        public virtual ICollection Books
        {
            get { return _books ?? (_books = new Collection()); }
            set { _books = value; }
        }
    
        public void AddBook(Book book)
        {
            book.Author = this;
            Books.Add(book);
        }
    }
    

    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.

提交回复
热议问题