gpt4 book ai didi

entity-framework - Entity Framework : Cannot be configured on 'xxx' class because it is a derived type

转载 作者:行者123 更新时间:2023-12-05 02:13:41 30 4
gpt4 key购买 nike

当我尝试自己添加“AppUserRoles”表以从用户访问 UserRoles 时出现此错误,例如:

from u in _userManager.Users.Where(x => x.UserRoles "contain" "some codition here")

我得到了这个错误:

A key cannot be configured on 'AppUserRoles' because it is a derived type. The key must be configured on the root type 'IdentityUserRole'. If you did not intend for 'IdentityUserRole' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.

这是我之前的代码,运行正常:

builder.Entity<IdentityUserRole<Guid>>().ToTable("AppUserRoles")
.HasKey(x => new { x.RoleId, x.UserId });

--->我改成这样:

我的用户类

[Table("AppUsers")]
public class AppUser : IdentityUser<Guid>, IDateTracking, ISwitchable
{
public virtual ICollection<AppUserRoles> UserRoles { get; set; }
}

我的角色类

[Table("AppRoles")]
public class AppRole : IdentityRole<Guid>
{
public virtual ICollection<AppUserRoles> UserRoles { get; set; }
}

我的 appUserRole 类:

[Table("AppUserRoles")]
public class AppUserRoles : IdentityUserRole<Guid>
{

public virtual AppUser User { get; set; }
public virtual AppRole Role { get; set; }
}

我的 DbContextClass

public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<AppUser> AppUsers { get; set; }
public DbSet<AppRole> AppRoles { get; set; }
public DbSet<AppUserRoles> AppUserRoles { get; set; }

protected override void OnModelCreating(ModelBuilder builder)
{
#region Identity Config

builder.Entity<IdentityUserClaim<Guid>>().ToTable("AppUserClaims").HasKey(x => x.Id);

builder.Entity<IdentityUserLogin<Guid>>().ToTable("AppUserLogins").HasKey(x => x.UserId);

builder.Entity<AppUserRoles>(userRole =>
{
userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

userRole.HasOne(ur => ur.Role)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();

userRole.HasOne(ur => ur.User)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
});

builder.Entity<IdentityUserToken<Guid>>().ToTable("AppUserTokens")
.HasKey(x => new { x.UserId });

#endregion Identity Config

}

public override int SaveChanges()
{
var modified = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified || e.State == EntityState.Added);

foreach (EntityEntry item in modified)
{
var changedOrAddedItem = item.Entity as IDateTracking;
if (changedOrAddedItem != null)
{
if (item.State == EntityState.Added)
{
changedOrAddedItem.DateCreated = DateTime.Now;
}
changedOrAddedItem.DateModified = DateTime.Now;
}
}
return base.SaveChanges();
}
}

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
var builder = new DbContextOptionsBuilder<AppDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new AppDbContext(builder.Options);
}
}

这是我的启动文件:

services.AddDbContext<AppDbContext>(options =>

options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
o => o.MigrationsAssembly("YayoiApp.Data.EF")),
ServiceLifetime.Scoped);

请给我一些建议,我已经研究了很多,但没有找到解决方案。谢谢。

最佳答案

定制IdentityUserRole<Guid> , 你需要改变你的 DbContext喜欢

public class ApplicationDbContext : IdentityDbContext<AppUser
, AppRole
, Guid
, IdentityUserClaim<Guid>
, AppUserRoles
, IdentityUserLogin<Guid>
, IdentityRoleClaim<Guid>
, IdentityUserToken<Guid>>
{

然后在Startup.cs中注册

services.AddIdentity<AppUser, AppRole>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();

用例:

public class HomeController : Controller
{
private readonly UserManager<AppUser> _userManager;
private readonly RoleManager<AppRole> _roleManager;
public HomeController(UserManager<AppUser> userManager
, RoleManager<AppRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
public async Task<IActionResult> Index()
{
var userName = "Tom";
var passWord = "1qaz@WSX";
var appUser = new AppUser
{
UserName = userName
};
await _userManager.CreateAsync(appUser, passWord);
var roleName = "Admin";
await _roleManager.CreateAsync(new AppRole { Name = roleName });
await _userManager.AddToRoleAsync(appUser, roleName);
var roles = appUser.UserRoles;
return View();
}

关于entity-framework - Entity Framework : Cannot be configured on 'xxx' class because it is a derived type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54718843/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com