c# - 实体框架代码优先以意外方式生成表/键
问题描述
我有很多代表表格的类,但其中三个让我头疼: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 个正确?你能看出我做错了什么吗?
解决方案
有时默认映射不是我们想要的,所以我们必须明确告诉 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);
}
推荐阅读
- python - Pandas 聚合函数字典弃用更改
- laravel - 在 laravel 7 中更改默认语言(本地化)的问题
- python - 如何检查字符串是否包含字符串的完全匹配?
- node.js - 赛普拉斯 cy.wait 不适用于 AWS CodeBuild
- sql - 用于将行转换为列的 SQL 选择查询
- javascript - 将html表格中的单元格从简单文本更改为超链接
- html - 试图垂直翻转
在一个里面 - javascript - 我被困在创建一个新的 Leaflet 自定义控件
- c# - 反序列化字符串数组以列出 C#
- flutter - 如果我将文件放在 getApplicationDocumentsDirectory() 目录中,文件将存储在哪里?它会增加应用程序的大小吗?