Entity Framework 4.1 InverseProperty Attribute and ForeignKe
本文关键字:Attribute and ForeignKe InverseProperty Framework Entity | 更新日期: 2023-09-27 17:53:32
我将使用外键在Employee和Team实体之间创建两个引用。所以我定义了两个实体如下
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
[ForeignKey("FirstTeam")]
public int FirstTeamId { get; set; }
[InverseProperty("FirstEmployees")]
public virtual Team FirstTeam { get; set; }
[ForeignKey("SecondTeam")]
public int SecondTeamId { get; set; }
[InverseProperty("SecondEmployees")]
public virtual Team SecondTeam { get; set; }
}
public class Team
{
public int Id { get; set; }
public string TeamName { get; set; }
[InverseProperty("FirstTeam")]
public virtual ICollection<Employee> FirstEmployees { get; set; }
[InverseProperty("SecondTeam")]
public virtual ICollection<Employee> SecondEmployees { get; set; }
}
我认为理论上是正确的,但它显示了异常如下:
{"Introducing FOREIGN KEY constraint 'Employee_SecondTeam' on table 'Employees' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.'r'nCould not create constraint. See previous errors."}
有人能帮我吗?提前感谢Kwon
这在理论上是正确的,但SQL服务器(不是实体框架)不喜欢它,因为你的模型允许单个员工成为第一和第二团队的成员。如果删除了Team
,将导致多个删除路径指向同一个Employee
实体。
这不能与级联删除一起使用,级联删除在EF代码中默认首先使用,如果您将外键定义为强制性的(不可为空的)。
如果你想避免异常,你必须使用流畅映射:
public Context : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Team> Teams { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>()
.HasRequired(e => e.SecondTeam)
.WithMany(t => t.SecondEmployees)
.HasForeignKey(e => e.FirstTeamId)
.WillCascadeOnDelete(false);
...
}
}
这将导致必须在删除团队之前手动删除SecondTeam成员的场景。
前面的答案都是正确的,但有一点是错误的
modelBuilder.Entity<Employee>()
.HasRequired(e => e.SecondTeam)
.WithMany(t => t.SecondEmployees)
.HasForeignKey(e => e.SecondTeamId) // mistake
.WillCascadeOnDelete(false);
FirstTeamId
而不是SecondTeamId
将导致SecondTeam navigation
属性始终为FirstTeam