实体框架核心两个对象作为主键

时间:2018-06-13 16:54:45

标签: 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; }
}    

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

modelBuilder.Entity<Relationship>().HasKey(r => new { r.User, r.Friend });

我收到一条错误消息:

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'.

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

1 个答案:

答案 0 :(得分:3)

这里的基本思想是您为EF可以用来建立关系的模型添加属性。你正在尝试创建User类型的关系并且正在创建错误。要分配组合键,每个键必须是与Key字段兼容的类型,而不是导航属性。因此,我们添加UserIdFriendIdint等类型的stringGUID,然后根据这些属性创建关系。

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

您现在可以在UserIdFriendId之间定义复合键。这样的事情应该做:

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

Source: Medium - How To: Entity Framework Core relationships, composite keys, foreign keys, data annotations, Code First and Fluent API

相关问题