2011-02-10 95 views
0

我有这个fellowing实体:使用实体框架4的实​​体和映射如何处理null(ICollection)?

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标签{获得;私人设置; }

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

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

谢谢。

回答

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; 

正如你看到的,当吸气首次调用集合初始化。

+0

你说得对,这是我的错。 – Rushino 2011-02-10 12:59:11