Entity Framework CTP5 Code-First Mapping - Foreign

2019-01-26 16:04发布

How would I map something like this using the modelBuilder? Where theres a nullable foreign key referencing the same tables primary key

Table: Task
taskID int pk
taskName varchar
parentTaskID int (nullable) FK

Task class:

public class Task
{
     public int taskID {get;set;}
     public string taskName {get;set;}
     public int parentTaskID {get;set;}
     public Task parentTask {get;set;}
}

...

    modelBuilder.Entity<Task>()
        .HasOptional(o => o.ParentTask)....

1条回答
欢心
2楼-- · 2019-01-26 16:57

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);
    }
}
查看更多
登录 后发表回答