如何为一个模型创建两个导航属性(EF6 Code First)

时间:2013-11-16 16:02:35

标签: c# .net code-first entity-framework-6

使用EF6 Code First约定,我想创建具有两个外键的模型到同一个表。例如,现在我有团队模型:

public class Team
{
    public Guid Id { get; set; }
    public String Name { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}

匹配型号:

public class Match
{
    public Guid Id { get; set; }
    public Int32 TeamHomeScore { get; set; }
    public Int32 TeamAwayScore { get; set; }

    public Guid TeamHomeId { get; set; } // I want these properties to be foreign keys
    public Guid TeamAwayId { get; set; } //

    public virtual Team TeamHome { get; set; }
    public virtual Team TeamAway { get; set; }
}

但是在项目运行后,我有下一个例外:

  

在表'匹配'上引入FOREIGN KEY约束'FK_dbo.Matches_dbo.Teams_TeamHomeId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。   无法创建约束。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

如果您使用迁移,请尝试此操作。每次迁移都不聪明,有时你应该输入代码。

public class Match
{
    public Guid Id { get; set; }
    public Int32 TeamHomeScore { get; set; }
    public Int32 TeamAwayScore { get; set; }

    public Guid TeamHomeId { get; set; } // I want these properties to be foreign keys
    public Guid TeamAwayId { get; set; } //

    [ForeginKey("TeamHomeId")]
    public virtual Team TeamHome { get; set; }
    [ForeginKey("TeamAwayId")]
    public virtual Team TeamAway { get; set; }
}

然后您将在下面添加到DataContex.cs

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
modelBuilder.Entity<Match>()
               .HasRequired(a => a.TeamHome )
               .WithMany()
               .HasForeignKey(u => u.TeamHomeId);

modelBuilder.Entity<Match>()
               .HasRequired(a => a.TeamAway )
               .WithMany()
               .HasForeignKey(u => u.TeamAwayId);
}

答案 1 :(得分:1)

SQL Server返回错误,因为它无法处理多个级联路径。多路径是匹配,其中包含许多团队属性。

将delete上的级联设置为false。

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Match>()
                    .HasRequired<Team>(i => i.TeamHome)
                    .WithMany(i => i.Matches)
                    .WillCascadeOnDelete(false);

        base.OnModelCreating(modelBuilder);
    }

由于没有级联删除,您必须先删除团队的匹配,然后再删除团队。