Entity Framework Core 自引用可选属性

3

我正在使用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 Core中我该如何做呢? 以下是我的流畅映射:

modelBuilder.Entity<Category>(e =>
{
    e.HasKey(c => c.CategoryId);

    e.Property(c => c.DateCreated).ValueGeneratedOnAdd();
    e.Property(c => c.DateModified).ValueGeneratedOnAddOrUpdate();
});
1个回答

3

基于它可以为空,你的ParentCategoryId已经是可选项了。如果它不能为null,那它就是必填项。你不需要进一步配置。

请注意,你不需要将CategoryId配置为Category的键。它会被配置为键,因为它已经符合实体键的命名约定。


EF会知道可空的ParentCategoryID是该属性的外键吗? - Daniel
它应该可以做到 - 我还没有在自引用关系上使用EF Core进行测试 - 除了检查我在EF6文章中概述的方法是否有效。为了保险起见,我建议将ParentCategory重命名为Parent,并添加一个Children属性,它将是一个List<Category> - Mike Brind

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接