Entity Framework 4.1 Code First - Should many relationship ICollections be initialised

馋奶兔 提交于 2019-12-06 05:52:43

问题


In Entity Framework 4.1 when creating a POCO, should the class be coded to initialise the Many relationships or is there some reason to allow the Entity Framework to have control over these properties?

public class Portfolio
{
    private ICollection<Visit> _visits;

    public virtual ICollection<Visit> Visits
    {
        get
        {
            if (_visits == null)
            {
                _visits = new List<Visit>();
            }
            return _visits;
        }
        set
        {
            _visits = value;
        }
    }
}

Or

public class Portfolio 
{
    public virtual ICollection<Visit> Visits
    {
        get;
        set;
    }
}

Is there a better pattern still?


回答1:


The first version is correct. It will allow you to initialize collection when you are creating a new entity but in the same time it will allow EF to initialize the collection when it materializes the entity loaded from DB and wrapps it by dynamic proxy for lazy loading.



来源:https://stackoverflow.com/questions/5703761/entity-framework-4-1-code-first-should-many-relationship-icollections-be-initi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!