【发布时间】:2022-08-19 13:23:55
【问题描述】:
我正在尝试创建一对多的 beetwen IdentityUser 模型(继承自 IdentityUser 类)和 Comment 模型,但出现错误:The relationship from \'Comment.WebAppUser\' to \'WebAppUser.Comments\' with foreign key properties {\'UserId\' : int} cannot target the primary key {\'Id\' : string} because it is not compatible. Configure a principal key or a set of foreign key properties with compatible types for this relationship. 问题是 IdentityUser 模型使用 string 作为主键但在 Comment用户 id 的外键模型类型为int。
问题是:我应该如何解决这个冲突?我是否应该为 int 更改 IdentityUser 主键的类型(我知道我可以做到,但这不会因为IdentityUser 基类及其结构而产生问题吗?) 或者可能将外键转换为字符串?
public class Comment
{
[Key]
public int CommentId { get; set; }
public int UserId { get; set; }
public WebAppUser WebAppUser { get; set; }
}
public class WebAppUser : IdentityUser
{
public IEnumerable<Comment> Comments { get; set; }
}
modelBuilder.Entity<Comment>()
.HasOne<WebAppUser>(w => w.WebAppUser)
.WithMany(c => c.Comments)
.HasForeignKey(w => w.UserId);
如果选项是更改 WebApp User 表的主键,请告诉我后果是什么,以及我必须在代码中更改/添加的内容和位置。
标签: entity-framework asp.net-core-webapi .net-6.0