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

前端 未结 1 1295
甜味超标
甜味超标 2020-12-19 15:24

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 in         


        
相关标签:
1条回答
  • 2020-12-19 15:41

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题