【问题标题】:How to create relation one to many between IdentityUser model and another model (Keys type difference)如何在 IdentityUser 模型和另一个模型之间创建一对多的关系(键类型差异)
【发布时间】: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


    【解决方案1】:

    Fk改成字符串,改WebAppUserprimary key的类型都是可行的方法,但是如果选择在WebAppUser中更改PK的类型,则需要按照如下修改代码:

    Model

    public class WebAppUser : IdentityUser<int>
        {
            public IEnumerable<Comment> Comments { get; set; }
        }
    

    改变:

    public class ApplicationDbContext : IdentityDbContext
    

    public class ApplicationDbContext : IdentityDbContext<WebAppUser,IdentityRole<int>,int>
    

    Startup.cs

    services.AddDefaultIdentity<WebAppUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    现在你将 pk 的类型更改为int 成功。

    在我看来,将 FK 更改为字符串比将 IdentityUser 中的 PK 更改为 int 更容易。

    更多细节可以参考这个link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 2023-03-27
      • 1970-01-01
      • 2017-06-10
      相关资源
      最近更新 更多