【问题标题】:How to remove the duplication of UserId column in ASP.NET identity如何删除 ASP.NET 标识中重复的 UserId 列
【发布时间】:2021-12-29 18:52:49
【问题描述】:

在我的 .NET 项目中,我创建了一个类“ApplicationUser”,它像这样从 IdentityUser 继承

{
   public class ApplicationUser : IdentityUser
   {
       public ICollection<Task> Tasks { get; set; }
       public ICollection<Category> Categories { get; set; }
   }
} 

并像这样与“类别”类建立一对多关系:

namespace ToDo.Models
{
    public class Category
    {
        public int CategoryId { get; set; }
        [Required(ErrorMessage = "Category Name is required.")]
        public string CategoryName { get; set; }
        public string UserId { get; set; }
        public ICollection<Task> Tasks { get; set; }
        public ApplicationUser ApplicationUser { get; set; }
    }
}

但是当我创建一个新类别时,它会进入数据库,其中包含两列 Id,第一列是 UserId,第二列是 ApplicationUserId,这是我没有创建的,有人可以帮帮我吗? 提前致谢。 还有一张来自数据库的图片

【问题讨论】:

  • 你不能从你的模型中删除 UserId col 吗?
  • ApplicationUser 模型不包含 ApplicationUserId 属性,它继承自 IdentityUser
  • 问题解决了吗?

标签: c# asp.net asp.net-mvc asp.net-core asp.net-identity


【解决方案1】:

按照惯例,EF 会将外键创建为“{NavigationProperty}Id”,因此 EF 将 ApplicationUserId 创建为您的外键。它只是认为 UserId 是您出于自己的目的添加到类中的一些值。

您可以将 EF 配置为专门使用 UserId 作为 Fluent API 中 ApplicationUser 的 FK:

builder.Entity<Category>()
    .HasOne<ApplicationUser>(p => p.ApplicationUser)
    .WithMany()
    .HasForeignKey(p => p.UserId);

或使用注解:

[ForeignKey("UserId")]
public ApplicationUser ApplicationUser { get; set; }

【讨论】:

    猜你喜欢
    • 2011-04-29
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    相关资源
    最近更新 更多