gpt4 book ai didi

c# - Entity Framework Core 两个对象作为主键

转载 作者:太空狗 更新时间:2023-10-30 01:13:13 26 4
gpt4 key购买 nike

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

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

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

[Required]
public DateTimeOffset RelationshipInitializationDate { get; set; }
}

用户的 ID 将有多个记录,并且将有多个记录具有相同的 FriendID,因此将其中任何一个定义为键是不行的。我希望 key 是 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'.

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

最佳答案

此处的基本思想是将属性添加到 EF 可用于建立关系的模型。是的,您正在尝试创建 User 类型的关系,这会产生错误。要分配复合键,每个键的类型必须与 Key 字段兼容,而不是导航属性。所以我们添加 UserIdFriendId 类型 int, 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

关于c# - Entity Framework Core 两个对象作为主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50842509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com