4

在我的数据库中,我有一个表类别,列Id,CategoryName,ParentCategoryId,其中ParentCategoryId对Category.Id有一个约束。EF Code First中自引用实体的映射

我使用实体框架代码首先,在实体的样子:

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属性。

如何才能告诉代码首先使用正确的导航属性?

+0

非常类似的问题在这里: http://stackoverflow.com/a/4812413/97803 – 2016-06-27 22:49:13

回答

6

你的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); 
    } 
} 
+0

正如你建议我尝试“modelBuilder.Entity ()的hasMany(类别=> category.SubCategories).WithRequired(category => category.ParentCategory).HasForeignKey(category => category.Id).WillCascadeOnDelete(false);'事实上,这也是有效的。我更喜欢你的方法,它是强类型的!谢谢! – 2012-03-13 13:07:46

+0

或者它应该是WithOptional而不是WithRequired ...? – 2012-03-13 13:15:18

+1

@路德,是的,对不起,它应该是WithOptional。 – bdparrish 2012-03-13 13:17:27

0

我想我找到了,我加在OnModelCreating操作如下:

modelBuilder.Entity<Domain.Entities.Category>().HasOptional<Category>(c => c.ParentCategory).WithMany().Map(m => m.MapKey(new string[] { "Id", "ParentCategoryId" })); 

现在ParentCategory和子类性质的工作(我可以删除组别和类别2)。不知道为什么子类的作品,虽然...

4

实体框架6处理此。您必须确保使用[Key]注释来标识主键。不确定它是否适用于虚拟关键字。

public class Category 
{ 
    [Key] 
    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 ICollection<Category> SubCategories { get; private set; } 
}