【问题标题】:Entity and mapping using Entity Framework 4 how to handle null (ICollection)?使用Entity Framework 4的实体和映射如何处理null(ICollection)?
【发布时间】:2011-02-10 00:59:13
【问题描述】:

我有这个伙伴实体:

 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。我无法初始化它,因为它需要是虚拟的。

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

谢谢。

【问题讨论】:

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


    【解决方案1】:

    即使它是虚拟的,你也可以初始化(实际上你必须)。这是从 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 时会初始化集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2010-10-07
      • 2018-01-21
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多