gpt4 book ai didi

c# - EF Code First 中自引用实体的映射

转载 作者:太空狗 更新时间:2023-10-29 21:06:11 24 4
gpt4 key购买 nike

在我的数据库中,我有一个表 Category,其中包含列 Id、CategoryName、ParentCategoryId,其中 ParentCategoryId 对 Category.Id 有约束。

我首先使用实体​​框架代码,其中实体看起来像:

public class Category
{
public long Id { get; private set; }
public string CategoryName { get; private set; }
public long? ParentCategoryId { get; private set; }
public Category ParentCategory { get; private set; }
public virtual ICollection<Category> SubCategories { get; private set; }
}

如果我尝试对此运行查询,我会得到异常:

 The relationship 'ComplaintModel.FK_Complaint_Category' was not loaded because the type 'ComplaintModel.Category' is not available.\r\nThe following information may be useful in resolving the previous error:\r\nThe required property 'Category1' does not exist on the type 'EC.Complaint.Services.Command.Domain.Entities.Category'.\r\n\r\n"}    System.Exception {System.Data.MetadataException}

所以它似乎需要导航属性,如果我添加这些:

 public ICollection<Category> Category1 { get; private set; }
public long? Category2Id { get; private set; }
public Category Category2 { get; private set; }

查询有效。

当然,我不想要 Category1 和 Category2 属性,我想要使用 ParentCategory 和 SubCategories 属性。

如何让代码首先使用正确的导航属性?

最佳答案

你的 POCO 类应该是这样的......

public class Category
{
public long Id { get; private set; }
public string CategoryName { get; private set; }
public long? ParentCategoryId { get; private set; }
public virtual Category ParentCategory { get; private set; }
public virtual ICollection<Category> SubCategories { get; private set; }
}

public class CategoryConfiguration : EntityTypeConfiguration<Category>
{
public CategoryConfiguration()
{
this.HasKey(x => x.Id);

this.HasMany(category => category.SubCategories)
.WithOptional(category => category.ParentCategoryId)
.HasForeignKey(course => course.UserId)
.WillCascadeOnDelete(false);
}
}

关于c# - EF Code First 中自引用实体的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9683716/

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