首页 > 解决方案 > 实体框架代码优先以意外方式生成表/键

问题描述

我有很多代表表格的类,但其中三个让我头疼:Person、Task 和 Role,下面是它们的代码:

public class Person : BaseModel
{
        public int Id { get; set; }
        public string FName { get; set; }
        public string LName { get; set; }
        public string Title { get; set; }

        public ICollection<TestEvent> TestEventsLed { get; set; }
        public ICollection<TestEvent> TestEventsCreated { get; set; }
        public ICollection<Program> ProgramsLed { get; set; }
        public ICollection<Task> TasksCreated { get; set; }
        public ICollection<PersonalEvent> PersonalEventsCreated { get; set; }

        public virtual ICollection<Role> RolesHeld { get; set; }
        public virtual ICollection<Task> TasksAssigned { get; set; }
}

public class Role : BaseModel
{
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Person> PeopleWithThisRole { get; set; }
}

public class Task : BaseModel
{
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime SuspenseDatetime { get; set; }
        public DateTime CreatedDatetime { get; set; }
        public int CreatedById { get; set; }
        public bool Completed { get; set; }
        public bool Archived { get; set; }

        public Person CreatedBy { get; set; }

        public virtual ICollection<Person> PeopleAssigned { get; set; }
}

我最终得到的主要是我想要的,除了一些小问题:

Expected:                                       Actual:
- People should have 0 foreign keys, just       - People has 1 FK and 1 extra column out of
  2 many-to-manys for RolesHeld and               nowhere: Task_Id and the FK is for that
  TasksAssigned                                   new column referencing Id in Tasks?

- Task should have 1 foreign key for            - Task has 2 extra columns out of nowhere
  CreatedById linked to a Person                  called Person_Id and Person_Id1 and then
                                                  identical foreign keys attached to them
                                                  (and it has the expected CreatedById FK)

- There should be a RolePersons table           - This part happened correctly and with the 
  with 2 FKs to represent the many-to-many        correct FKs to represent the many-to-many

- There should be a TaskPersons table           - There is no new table at all for this
  with 2 FKs to represent the many-to-many  

奇怪的是,我以同样的方式做了其中的一些(比如两个多对多关系),但结果只有 1 个正确?你能看出我做错了什么吗?

标签: c#entity-frameworkentity-framework-6ef-code-first

解决方案


有时默认映射不是我们想要的,所以我们必须明确告诉 EF 我们需要什么。只需将此方法添加到您的 DbContext 中,它就可以按要求工作:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>().HasMany(p => p.TasksAssigned).WithMany(t => t.PeopleAssigned);
    modelBuilder.Entity<Person>().HasMany(p => p.TasksCreated).WithRequired(t => t.CreatedBy).WillCascadeOnDelete(false);
}

推荐阅读