gpt4 book ai didi

c# - Entity Framework ..如何映射自引用外键..例如类别有很多类别

转载 作者:行者123 更新时间:2023-11-30 17:21:14 26 4
gpt4 key购买 nike

我有以下 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);
}
}

请注意“Parent”属性以及我如何不使用“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 是一大堆其他对象的父对象,也没有意识到它们需要持久化。我有一个解决方法,它是“父”类别属性中注释掉的代码。但我宁愿不必这样做,因为感觉不对。

任何帮助将不胜感激

jack

最佳答案

这是可能的,但您必须使用跟踪代理。为此,请修改您的类别类,以便所有 持久属性都是虚拟的。

public class Category 
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
}

创建上下文并检查是否允许创建动态代理。在这种情况下,您可以使用 CreateObject 方法来获取您的类别实例。您不会获得类别类型的实例,而是从类别继承的动态类型。这个动态代理负责延迟加载(如果启用)和对现有上下文的更改跟踪。如果您在一侧修改导航属性,它将自动修改另一侧的导航属性。

using (var context = new ObjectContext(connectionString))
{
// This should be default value
context.ContextOptions.ProxyCreationEnabled = true;

var cat0 = context.CreateObject<Category>();
cat0.Name = "A";

var cat1 = context.CreateObject<Category>();
cat1.Name = "B";
cat1.Parent = cat0;

context.CreateObjectSet<Category>().AddObject(cat0);
context.SaveChanges();
}

编辑:

如果您不喜欢使用跟踪代理(需要现有上下文)的方法,您可以颠倒创建实体的方式。不必在子项上设置 Parent 属性,而必须在父项上填充 Childs。在这种情况下,它将起作用。

关于c# - Entity Framework ..如何映射自引用外键..例如类别有很多类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3634996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com