如何确保具有不同数据类型的两个属性的组合键?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);
看到您的流畅配置后,您的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);