IdentityDbContext 抛出错误 "The entity type 'User' requires a primary key to be defined."
IdentityDbContext throws error "The entity type 'User' requires a primary key to be defined."
我想为我的应用程序创建 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; }
}
现在我使用身份创建用户实体和用户角色 class:
public class UserRoleEntity : IdentityRole<Guid>
{
public UserRoleEntity()
: base()
{
}
public UserRoleEntity(string roleName)
: base(roleName)
{
}
}
用户实体class:
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.check 图片时出现错误:
Error image
这是我的 product.cs class:
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.csclass:-
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: The entity type 'User' requires a primary key to be defined.
Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model)
Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model)
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
第一个用户实体模型有 ID?在您的 userentity 代码中,您没有分配 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 作为主键并分配值
我想为我的应用程序创建 Identityuser。我使用 Identitydbcontext
.
这是我的代码 - 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; }
}
现在我使用身份创建用户实体和用户角色 class:
public class UserRoleEntity : IdentityRole<Guid>
{
public UserRoleEntity()
: base()
{
}
public UserRoleEntity(string roleName)
: base(roleName)
{
}
}
用户实体class:
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.check 图片时出现错误:
Error image
这是我的 product.cs class:
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.csclass:-
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: The entity type 'User' requires a primary key to be defined.
Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model)
Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model)
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
第一个用户实体模型有 ID?在您的 userentity 代码中,您没有分配 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 作为主键并分配值