我正在使用 Microsoft.EntityFrameworkCore.Sqlite v1.0.1。 这是我的实体:
public class Category
{
public int CategoryId { get;set;}
public Category ParentCategory { get; set; }
public int? ParentCategoryId { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
所以我需要将 ParentCategory 配置为可选属性。我如何在 EF 核心中执行此操作? 这是我到目前为止的流利映射:
modelBuilder.Entity<Category>(e =>
{
e.HasKey(c => c.CategoryId);
e.Property(c => c.DateCreated).ValueGeneratedOnAdd();
e.Property(c => c.DateModified).ValueGeneratedOnAddOrUpdate();
});
最佳答案
您的 ParentCategoryId
已经是可选的,因为它可以为空。如果它不可为空,则它是必需的。您无需进一步配置它。
请注意,您不需要将 CategoryId
配置为 Category
的 Key。它将被配置为键,因为它已经遵循实体键的命名约定。
关于c# - Entity Framework Core 自引用可选属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953860/