本文介绍了实体框架CTP5 Code-First Mapping - 同一表中的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用modelBuilder映射这样的东西?其中theres是可空的外键引用相同的表主键
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
任务类:
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)....
推荐答案
以下代码为您提供了所需的模式。请注意,您还需要将 ParentTaskID
外键定义为可空整数,如下所示。
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);
}
}
这篇关于实体框架CTP5 Code-First Mapping - 同一表中的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!