我有Category可以有RootCategory。问题是它没有正确设置RootCategoryID,而是在我的模型中甚至没有创建的数据库中创建Category_ID

如果我没有在RootCategory上修改get,它将按我的期望进行映射。但是RootCategory始终为空(他不知道从何处获取它)

模型

public class Category
{
    public int ID { get; set; }
    // Tried [ForeignKey("RootCategoryID")]
    public Category RootCategory {
        get
        {
            ORDataContext _db = new ORDataContext();
            return _db.Categories.Where(x => x.ID == this.RootCategoryID).SingleOrDefault();
        }
    }
    public int? RootCategoryID { get; set; } // This does not set itself properly

    public ICollection<Category> ChildCategories { get; set; }
}


update-database之后生成的数据库

-ID
-RootCategoryID (that I have created, but it's not used)
-Category_ID (taht EF created for me, that I don't want)

最佳答案

您不需要像手动那样手动加载nav属性RootCategory,EF会自动执行。但是,EF无法推断出您想要的内容,您应该使用数据注释将其显式映射:

   public class Category
   {
      public int ID { get; set; }

      public virtual Category RootCategory { get; set; }
      [ForeignKey("RootCategory")]
      public int? RootCategoryID { get; set; } // This does not set itself properly

      public virtual ICollection<Category> ChildCategories { get; set; }

   }


或通过流利:

  protected override void OnModelCreating( DbModelBuilder modelBuilder )
  {
     modelBuilder.Entity<Category>()
        .HasMany( c => c.ChildCategories )
        .WithOptional( ca => ca.RootCategory )
        .HasForeignKey( c => c.RootCategoryID );
  }


并且您的所有财产/收藏都应该可以使用。

09-07 01:07