加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:54:22 所属栏目:百科 来源:网络整理
导读:在我的数据库中,我有一个表类别,列ID,CategoryName,ParentCategoryId,其中ParentCategoryId对Category.Id有约束. 我首先使用实体??框架代码,实体看起来像: public class Category{ public long Id { get; private set; } public string CategoryName { get;
在我的数据库中,我有一个表类别,列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.rnThe following information may be useful in resolving the previous error:rnThe required property 'Category1' does not exist on the type 'EC.Complaint.Services.Command.Domain.Entities.Category'.rnrn"}    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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读