Entity Framework Core 两个对象作为主键

Phi*_*len 5 c# asp.net-mvc entity-framework-core

我有一个用于管理朋友关系的模型。它看起来如下:

public class Relationship
{   
   [Required]
   public User User { get; set; }

   [Required]
   public User Friend { get; set; }

   [Required]
   public DateTimeOffset RelationshipInitializationDate { get; set; }
}    
Run Code Online (Sandbox Code Playgroud)

用户的 ID 将有多个记录,并且会有多个记录具有相同的 FriendID,因此将其中任何一个定义为键是不行的。我希望密钥是 User 和 Friend 之间的组合,但是当我这样定义它时:

modelBuilder.Entity<Relationship>().HasKey(r => new { r.User, r.Friend });
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,指出:

The property 'Relationship.User' is of type 'User' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Run Code Online (Sandbox Code Playgroud)

我应该如何去创建将与用户和朋友对象链接的主键。我的其他具有类型属性的对象没有任何问题,如果我向关系模型添加任意键,我也没有问题。提前致谢

JSt*_*ard 7

这里的基本思想是向模型添加属性,EF 可以使用这些属性来建立关系。是的,您正在尝试创建类型关系,User这正在创建错误。要分配复合键,每个键都需要是与Key字段兼容的类型,而不是导航属性。所以我们添加UserIdFriendId类型intstringGUID等,并从这些属性创建一个关系。

public class Relationship
{
    public User Friend { get; set; }

    public User User { get; set; }

    public int FriendId { get; set; }

    public int UserId { get; set; }

    public DateTimeOffset RelationshipInitializationDate { get; set; }
}

public class User
{
    public int UserId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您现在可以跨UserId和定义复合键FriendId。这样的事情应该做:

public class NorthwindContext : DbContext
{
     public NorthwindContext(DbContextOptions<NorthwindContext> options):base(options) { }

     public NorthwindContext() { }

     protected override void OnModelCreating(ModelBuilder builder)
     {
         builder.Entity<Relationship>().HasKey(table => new {
         table.FriendId, table.UserId
         });
     }
     public DbSet<Relationship> Relationships { get; set; }
     public DbSet<User> Users { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

来源:Medium - How To:Entity Framework Core 关系、复合键、外键、数据注释、Code First 和 Fluent API