Entity Framework CTP5 Code-First Mapping - Foreign Key in same table

て烟熏妆下的殇ゞ 提交于 2019-11-29 11:16:35

The following code gives you the desired schema. Note that you also need to define ParentTaskID foreign key as a nullable integer, like I did below.

public class Task
{
    public int TaskID { get; set; }
    public string TaskName { get; set; }        
    public int? ParentTaskID { get; set; }
    public Task ParentTask { get; set; }
}

public class Context : DbContext
{
    public DbSet<Task> Tasks { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Task>()
                    .HasOptional(t => t.ParentTask)
                    .WithMany()
                    .HasForeignKey(t => t.ParentTaskID);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!