实体和映射使用Entity Framework 4如何处理null(ICollection)? [英] Entity and mapping using Entity Framework 4 how to handle null (ICollection)?
本文介绍了实体和映射使用Entity Framework 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标签{get;私人集合}
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 ?
谢谢。
推荐答案
即使它是虚拟的,也可以初始化(实际上你必须)。这是从POCO T4模板生成的代码:
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;
正如您所看到的,在getter首次调用时初始化集合。
As you see collection is initialized when getter is first called.
这篇关于实体和映射使用Entity Framework 4如何处理null(ICollection)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文