实例化1到多个关系的新集合属性 [英] Instantiating a new Collection Property for a 1 to Many Relationship

查看:60
本文介绍了实例化1到多个关系的新集合属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,您可以看到我们必须实例化DocumentLinks。从你的身边开始,你现在只有在有子记录的情况下才会设置和填充集合,但是如果没有子记录,你现在将它留空。

In the below code, as you can see we have to instantiate DocumentLinks. From yourside you currently instatiate and fill up the collection only if there are child records, but if there are no child records you currently leave it null.

建议是给我们实例化的集合对于DocumentLinks,当没有记录时,集合中的项目为零。保存我们必须为所有子属性实例化集合。

Suggestion is to give us instantiated collection with zero items in collection when no records exist for DocumentLinks. Saves us having to instantiate the collection for all the children properties.

    public class Document 
    {
        public virtual int DocumentID
        {
            get;
            set;
        }

        private ICollection<DocumentLink> _DocumentLinks;
        [ForeignKey("DocumentID")]
        public virtual ICollection<DocumentLink> DocumentLinks
        {
            get
            {
                if (_DocumentLinks == null)
                    _DocumentLinks = new ObservableCollection<DocumentLink>();

                return _DocumentLinks;

            }
            set
            {
                _DocumentLinks = value;
            }
        }
    }

 

推荐答案

这是我们考虑添加到EF的内容。如果你愿意,你可以随时实例的收集和任何你指定EF将只使用(默认情况下EF将使用的HashSet< T>所以你的代码会导致一些藏品是HashSet的和其他
是的ObservableCollection

This is something we have considered adding to EF. If you want you can always instantiate the collection and EF will just use whatever you assign (by default EF will use HashSet<T> so your code will result in some collections being HashSet and others being ObservableCollection.

我建议写下这样的内容:

I'd recommend writing something like this:

public class Document 
{
  public Document()
  {
    this.DocumentLinks = new ObservableCollection<DocumentLink>();
  }

  public virtual ICollection<DocumentLink> DocumentLinks { get; private set; }
}
    

~Rowan

 

 


这篇关于实例化1到多个关系的新集合属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆