Entity and mapping using Entity Framework 4 how to handle null (ICollection)?

纵饮孤独 提交于 2019-12-25 03:21:04

问题


I have this fellowing entity :

 public class Post
    {
        public long PostId { get; private set; }
        public DateTime date { get; set; }
        [Required]
        public string Subject { get; set; }
        public User User { get; set; }
        public Category Category { get; set; }
        [Required]
        public string Body { get; set; }

        public virtual ICollection<Tag> Tags { get; private set; }

        public Post()
        {
            Category = new Category();
        }

        public void AttachTag(string name, User user)
        {
            if (Tags.Count(x => x.Name == name) == 0)
                Tags.Add(new Tag { 
                    Name = name, 
                    User = user 
                });
            else
                throw new Exception("Tag with specified name is already attached to this post.");
        }

        public Tag DeleteTag(string name)
        {
            Tag tag = Tags.Single(x => x.Name == name);
            Tags.Remove(tag);

            return tag;
        }

        public bool HasTags()
        {
            return (Tags != null || Tags.Count > 0);
        }

The problem is with virtual ICollection Tags { get; private set; }

When there is no tags inside, it is actually show as null. I can't initialize it because it need to be virtual.

How to handle nulls in entities ? How Tags is initialized and where ?

Thanks.


回答1:


You can initialize (actually you must) even if it is virtual. This is a code which is generated from POCO T4 template:

[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Csob.Arm.EntityGenerator", "1.0.0.0")]
public virtual ICollection<TransactionCodeGroup> TransactionCodeGroups
{
    get
    {
        if (_transactionCodeGroups == null)
        {
            _transactionCodeGroups = new FixupCollection<TransactionCodeGroup>();
        }
        return _transactionCodeGroups;
    }
    set
    {
        _transactionCodeGroups = value;
    }
}
private ICollection<TransactionCodeGroup> _transactionCodeGroups;

As you see collection is initialized when getter is first called.



来源:https://stackoverflow.com/questions/4952343/entity-and-mapping-using-entity-framework-4-how-to-handle-null-icollection

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