EF Code First实现一对一而非多对多关系

时间:2017-04-27 10:14:22

标签: c# entity-framework dbcontext ef-migrations

我注意到我的EF Code First流畅的API映射存在奇怪的问题。我想创建两个多对多关系,但EF似乎没有看到我重载的OnModelCreating函数,按照自己的约定生成一个表,另一个converts to One-To-One relation

型号:

public partial class Task
{
    public Task()
    {
        ParentTasks = new HashSet<Task>();
        ChildTasks = new HashSet<Task>();
    }
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public byte Progress { get; set; }
    public int Priority { get; set; }
    public byte[] Attachment { get; set; }
    public string Url { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime? Deadline { get; set; }

    //Foreign keys
    public int ListId { get; set; }

    //Navigation properties
    public TodoList List { get; set; }
    public ICollection<Task> ParentTasks { get; set; }
    public ICollection<Task> ChildTasks { get; set; }
}

public partial class TodoList
{
    public TodoList()
    {
        Tasks = new HashSet<Task>();
        Users = new HashSet<ApplicationUser>();
    }
    public int Id { get; set; }
    [MaxLength(250)]
    public string ListName { get; set; }

    //Foreign keys
    public int? GroupId { get; set; }
    [MaxLength(128)]
    public string OwnerId { get; set; }

    //Navigation properties
    public ApplicationUser Owner { get; set; }
    public Group Group { get; set; }
    public ICollection<Task> Tasks { get; set; }
    /// <summary>
    /// List of the users that have this list shared.
    /// </summary>
    public ICollection<ApplicationUser> Users { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        TodoLists = new HashSet<TodoList>();
    }
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at most {1} characters long.", MinimumLength = 2)]
    [Display(Name = "Name")]
    public string FirstName { get; set; }
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at most {1} characters long.", MinimumLength = 2)]
    [Display(Name = "Surname")]
    public string LastName { get; set; }
    [MaxLength(1024*1024, ErrorMessage = "Max size: 1MB")]
    public byte[] Avatar { get; set; }

    //Navigation properties

    /// <summary>
    /// List of the shared todo lists with specific user.
    /// </summary>
    public ICollection<TodoList> TodoLists { get; set; }
}

和DbContext:

public class TodoDbContext : DbContext
{
    public TodoDbContext() : base("DefaultConnection")
    {
    }

    public DbSet<Task> Tasks { get; set; }
    public DbSet<TodoList> TodoLists { get; set; }
    public DbSet<Group> Groups { get; set; }
    public DbSet<ApplicationUser> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Task>()
            .HasMany<Task>(t => t.ParentTasks)
            .WithMany(t => t.ChildTasks)
            .Map(m =>
                m.MapLeftKey("TaskID")
                .MapRightKey("ParentID")
                .ToTable("TaskCorrelations")
            );

        modelBuilder.Entity<TodoList>()
            .HasMany<ApplicationUser>(t => t.Users)
            .WithMany(a => a.TodoLists)
            .Map(m =>
                m.MapLeftKey("ListID")
                .MapRightKey("UserID")
                .ToTable("SharedTodoLists"));
    }

    public static TodoDbContext Create()
    {
        return new TodoDbContext();
    }
}

我是否需要手动“运行”此上下文? EF迁移系统甚至看不到我的DbContext中的更改。

编辑:这些是我用config做的事情:

  • 启用-迁移
  • 首先手动添加了迁移,但似乎没有用,所以我在
  • 上启用了自动迁移
  • AutomaticMigrationsEnabled = true;
  • AutomaticMigrationDataLossAllowed = true;

1 个答案:

答案 0 :(得分:1)

您应该像这样配置迁移:

<强> TodoDbContext

public class TodoDbContext : ApplicationDbContext
{
    /...
}

<强>配置

internal sealed class Configuration : DbMigrationConfiguration<TodoDbContext>
{
    public Configuration()
    {
        // ...
    }

    protected override void Seed(TodoDbContext context)
    {
        // ...
    }
}