映射在EF代码首先自我引用实体 [英] Mapping for self referencing entity in EF Code First

查看:300
本文介绍了映射在EF代码首先自我引用实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库我有一个表的类别,与列编号,类别名称,ParentCategoryId,其中ParentCategoryId对Category.Id的约束。

In my database I have a table Category, with columns Id, CategoryName, ParentCategoryId, where ParentCategoryId has a constraint on Category.Id.

我使用的是实体框架代码首先,在实体如下:

I'm using entity framework code first, where the entity looks like:

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; }
}

如果我试图运行对这一查询时,我得到的异常:

If I try to run a query against this, I get the exception:

 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}

所以,现在看来,这需要导航属性,如果我添加这些:

So it seems it needs navigation properties, if I add these:

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

查询工作。

但当然,我不希望组别和组别的属性,我想使用ParentCategory和子类别属性。

But of course, I don't want the Category1 and Category2 properties, I want ParentCategory and SubCategories properties being used.

我怎么能告诉代码首先要使用正确的导航属性?

How can I tell code first to use the correct navigation properties?

推荐答案

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

your POCO class should look like this ...

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);
    }
}

这篇关于映射在EF代码首先自我引用实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆