实体框架4.1 InverseProperty属性和ForeignKey的 [英] Entity Framework 4.1 InverseProperty Attribute and ForeignKey

查看:1861
本文介绍了实体框架4.1 InverseProperty属性和ForeignKey的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将创造员工和团队的实体与外键之间的两个引用。
所以我定义了两个实体如下

I will create two references between Employee and Team entities with foreign keys. So I defined two entities as follow

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; }
}

我认为这是正确的理论,但它表明了异常如下:

I thought it is correct theoretically, but it shows the Exception as follow :

{"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."}

任何人可以帮助我吗?

Can anybody help me?

在此先感谢

Thanks in advance Kwon

推荐答案

这在理论上是正确的,但因为你的模型允许一个员工是第一和第二两个团队的成员,SQL服务器(而不是实体框架)不喜欢。如果团队被删除,这将导致删除多路径相同员工实体。

It is theoretically correct but SQL server (not Entity framework) doesn't like it because your model allows single employee to be a member of both First and Second team. If the Team is deleted this will cause multiple delete paths to the same Employee entity.

这不能一起使用的级联删除这是在EF code默认使用第一,如果你定义外键的强制性(不能为空)。

This cannot be used together with cascade deletes which are used by default in EF code first if you define foreign key as mandatory (not nullable).

如果你想避免异常则必须使用流利的映射:

If you want to avoid the exception you must use fluent mapping:

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的成员。

This will result in scenario where you must delete members of SecondTeam manually before you delete the team.

这篇关于实体框架4.1 InverseProperty属性和ForeignKey的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆