Ef Core,具有不同数据类型的多对多连接表组合键

时间:2019-06-07 23:22:16

标签: c# entity-framework-core ef-fluent-api

如何确保具有不同数据类型的两个属性的组合键? EF Core抱怨;

具有外键属性{'UserId':string}的从'GroupUsers.Groups'到'Group.GroupUsers'的关系不能针对主键{'GroupId':int},因为它不是兼容。为此关系配置一个主键或一组兼容的外键属性。

我的表与以下类型不同的主键有很多关系

public class Group
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int GroupId { get; set; }

    [Required]
    public string GroupName { get; set; }

    public ICollection<GroupUsers> GroupUsers { get; set; }
}

public class User
{
    [Key]
    public string UserId { get; set; }

    public string Email { get; set; }

    public ICollection<GroupUsers> GroupUsers { get; set; }
}

public class GroupUsers
{
    public string UserId { get; set; }

    public int GroupId { get; set; }

    [ForeignKey("GroupId")]
    public Group Groups { get; set; }

    [ForeignKey("UserId")]
    public User Users { get; set; }
}

这是我忘记展示的流利的一面

     modelBuilder.Entity<GroupUsers>().HasKey(gu => new { gu.GroupId, gu.UserId});
     modelBuilder.Entity<GroupUsers>().HasOne(ub => ub.Users)
            .WithMany(x => x.GroupUsers).HasForeignKey(h => h.GroupId)
            .OnDelete(DeleteBehavior.SetNull);

      modelBuilder.Entity<GroupUsers>().HasOne(ub => ub.Groups)
            .WithMany(x => x.GroupUsers).HasForeignKey(h => h.UserId)
            .OnDelete(DeleteBehavior.Cascade);

1 个答案:

答案 0 :(得分:1)

看到您的流利配置后,您的HasForeignKey呼叫似乎已切换。

应该是:

modelBuilder.Entity<GroupUsers>().HasKey(gu => new { gu.GroupId, gu.UserId});
modelBuilder.Entity<GroupUsers>().HasOne(ub => ub.Users)
    .WithMany(x => x.GroupUsers).HasForeignKey(h => h.UserId)  // <-- change to this
    .OnDelete(DeleteBehavior.SetNull);

modelBuilder.Entity<GroupUsers>().HasOne(ub => ub.Groups)
    .WithMany(x => x.GroupUsers).HasForeignKey(h => h.GroupId)  // <-- change to this
    .OnDelete(DeleteBehavior.Cascade);