实体和映射使用Entity Framework 4如何处理null(ICollection)?

时间:2011-02-10 00:59:13

标签: entity-framework-4 code-first ef-code-first

我有这个同伴实体:

 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);
        }

问题在于虚拟ICollection标签{get;私人集; }

当里面没有标签时,它实际上显示为null。我无法初始化它,因为它需要是虚拟的。

如何处理实体中的空值?如何初始化标签以及在哪里?

感谢。

1 个答案:

答案 0 :(得分:3)

您可以初始化(实际上您必须),即使它是虚拟的。这是从POCO T4模板生成的代码:

[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;

如您所见,首次调用getter时会初始化集合。

相关问题