【发布时间】:2010-09-03 10:48:48
【问题描述】:
我有以下 poco 类:
public class Category : IDisplayName
{
private ICollection<Category> children;
private Category parent;
public Category()
{
children = new List<Category>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual Category Parent
{
get { return parent; }
set
{
parent = value;
// if (value != null && parent.Children.Contains(this) == false)
// {
// parent.Children.Add(this);
// }
}
}
public virtual ICollection<Category> Children
{
get { return children; }
set { children = value; }
}
}
这是映射文件(我不确定这是否正确..但我没有想法,所有文档都在那里......)
public class CategoryEntityConfiguration : EntityConfiguration<Category>
{
public CategoryEntityConfiguration()
{
Property(x => x.Name).IsRequired();
HasMany(x => x.Children).WithOptional(x => x.Parent);
HasOptional(x => x.Parent).WithMany(x => x.Children);
}
}
注意“父”属性以及我如何不使用“子”集合添加它们。
var cat_0 = new Category { Name = "Root" };
var cat_1 = new Category { Name = "Property", Parent = cat_0 };
var cat_2 = new Category { Name = "Property Services", Parent = cat_1 };
var cat_3 = new Category { Name = "Housing Association", Parent = cat_2 };
var cat_4 = new Category { Name = "Mortgages & Conveyancing", Parent = cat_2 };
var cat_5 = new Category { Name = "Property Management", Parent = cat_2 };
var cat_6 = new Category { Name = "Property Auctions", Parent = cat_2 };
var cat_7 = new Category { Name = "Landlords Wanted", Parent = cat_2 };
context.Set<Category>().Add(cat_0);
当我将 cat_0 保存到数据库中时,只插入了 1 行,而 Entity Framework 并没有发现 cat_0 是一大堆其他对象的父对象,并且没有意识到它们需要被持久化。我有一个解决方法,即“父”类别属性中注释掉的代码。但我宁愿不必这样做,因为感觉不对。
任何帮助将不胜感激
杰克
【问题讨论】:
标签: c# entity-framework poco