【问题标题】:IdentityDbContext throws error "The entity type 'User' requires a primary key to be defined."IdentityDbContext 抛出错误“实体类型'用户'需要定义主键。”
【发布时间】:2021-11-07 10:30:45
【问题描述】:

我想为我的应用程序创建 Identityuser。我使用 Identitydbcontext 创建 dbcontext。

这是我的代码 - ShopContext.cs 文件:

public class ShopContext: IdentityDbContext<UserEntity, UserRoleEntity, Guid>
{
    public ShopContext(DbContextOptions options)
         : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<UserEntity> Users { get; set; }
}

现在我使用身份创建用户实体和用户角色类:

public class UserRoleEntity : IdentityRole<Guid>
{
    public UserRoleEntity()
        : base()
    {
    }

    public UserRoleEntity(string roleName)
        : base(roleName)
    {
    }
}

用户实体类:

 public class UserEntity : IdentityUser<Guid>
{

    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTimeOffset CreatedAt { get; set; }
}

现在我尝试将数据输入到我的产品 DbSet 中,因为目前我没有实际的数据集 - 像这样:

public class SeedData
{

    public static async Task InitializeAsync(IServiceProvider services)
    {

        await AddTestData(
           services.GetRequiredService<ShopContext>(),
           services.GetRequiredService<UserManager<UserEntity>>());

        await AddTestUsers(
           services.GetRequiredService<RoleManager<UserRoleEntity>>(),
           services.GetRequiredService<UserManager<UserEntity>>());

    }

    private static async Task AddTestData(ShopContext shopContext, UserManager<UserEntity> userManager)
    {
        try
        {
            shopContext.Products.Add(new Product
            {
                Id = Guid.Parse("ee2b83be-91db-4de5-8122-35a9e9195976"),
                CategoryId = 1,
                Name = "Grunge Skater Jeans",
                Sku = "AWMGSJ",
                Price = 68,
                IsAvailable = true
            });

            var adminUser = userManager.Users

                .SingleOrDefault(u => u.Email == "admin@landon.local");

            await shopContext.SaveChangesAsync();

        }

        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

    private static async Task AddTestUsers(RoleManager<UserRoleEntity> roleManager, UserManager<UserEntity> userManager)
    {
        var dataExists = roleManager.Roles.Any() || userManager.Users.Any();
        if (dataExists)
        {
            return;
        }

        // Add a test role
        await roleManager.CreateAsync(new UserRoleEntity("Admin"));

        // Add a test user
        var user = new UserEntity
        {
            Id = Guid.Parse("ee2b83be-91db-4de5-8122-35a9e9195976"),
            Email = "admin@landon.local",
            UserName = "admin@landon.local",
            FirstName = "Admin",
            LastName = "Tester",
            CreatedAt = DateTimeOffset.UtcNow
        };

        await userManager.CreateAsync(user, "Supersecret123!!");

        // Put the user in the admin role
        await userManager.AddToRoleAsync(user, "Admin");
        await userManager.UpdateAsync(user);
    }
}

现在,当我尝试添加产品 dbset 时出现错误。请检查图像:

Error image

这是我的 product.cs 类:

public class Product
{
   
    public Guid Id { get; set; }
    public string Sku { get; set; }
    [Required]
    public string Name { get; set; }
    [MaxLength(255)]
    public string Description { get; set; }
    public decimal Price { get; set; }
    public bool IsAvailable { get; set; }

    public int CategoryId { get; set; }
    [JsonIgnore]
    public virtual Category Category { get; set; }
}

错误指出我在用户实体中缺少主键,但我已经为名字添加了键注释。

startup.cs 类中我的服务配置:-

 public void ConfigureServices(IServiceCollection services)
    {

        services.AddScoped<IProductService, ProductService>();
        services.AddScoped<IUserService, UserService>();

        services.AddDbContext<ShopContext>(
            options =>
            {
                options.UseInMemoryDatabase("landondb");
                options.UseOpenIddict<Guid>();

            });
                              

        // Add ASP.NET Core Identity
        AddIdentityCoreServices(services);           


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

private void AddIdentityCoreServices(IServiceCollection services)
    {
        var builder = services.AddIdentityCore<UserEntity>();
        builder = new IdentityBuilder(builder.UserType, typeof(UserRoleEntity), builder.Services);
        builder.AddRoles<UserRoleEntity>().AddEntityFrameworkStores<ShopContext>()
            .AddDefaultTokenProviders()
            .AddSignInManager<SignInManager<UserEntity>>();
    }

知道为什么我会收到此错误:-

InvalidOperationException:实体类型“用户”需要定义主键。

Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel 模型)
Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel 模型)
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext 上下文,IConventionSetBuilder 约定集构建器,IModelValidator 验证器)

【问题讨论】:

  • 请从 Userentity 类中删除 [key] 并尝试,默认情况下,Identity User 类定义了一个 Id 列。由于 EF 是基于约定的 ORM,任何名称为 Id 的列都将被视为主键。
  • 好的,我试试
  • 我已经在 userentity 类中添加了 ID,但仍然出现同样的错误。
  • 错误提示用户但你有 UserEntity 类?
  • @abdusco ......是的......你是对的......okye问题已解决。错误地我在订单类中使用了用户,而这个订单类与产品有关系。因此它给出了错误。谢谢....

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


【解决方案1】:

第一个用户实体模型有 id?并且在您的用户实体代码中,您没有分配 id 值, @sangita-paul 的代码是:

public class UserEntity : IdentityUser<Guid>
{

    [Key]
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
}

没有id,所以我认为userentity需要id作为主键和赋值

【讨论】:

  • 不,我没有在用户实体类中分配 id...我需要分配吗?
  • 如果您没有标识属性和赋值,则需要添加 id 属性
  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
  • 是的,我在 userentity.cs 中添加了 id,但我得到了同样的错误。请检查我的编辑代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2017-09-16
  • 2021-07-23
  • 2021-11-27
  • 2018-08-13
  • 2019-09-13
  • 1970-01-01
相关资源
最近更新 更多