Entity Framework CTP5 Code-First Mapping - foreign key in one table

How can I map something like this using modelBuilder? If theres is a null foreign key referencing the primary keys of the same tables

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)....
+4
source share
1 answer

The following code gives the desired circuit. Note that you also need to define the foreign key ParentTaskIDas an integer with a null value, as shown 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);
    }
}
+5
source

All Articles