Entity and mapping using Entity Framework 4 how to

2019-08-25 03:47发布

问题:

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.