【发布时间】: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 时出现错误。请检查图像:
这是我的 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