[英]ASP.NET Core- The DbContext of type 'ApplicationDbContext' cannot be pooled because it does not have a public constructor accepting a single parameter
我在 ASP.NET Core-6 Web API 中實現實體框架代碼優先。 我正在使用 IdentityDbContext,並且我有以下代碼:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, long, IdentityUserClaim<long>, ApplicationUserRole, IdentityUserLogin<long>, IdentityRoleClaim<long>, IdentityUserToken<long>>
{
private readonly ICurrentUserService _currentUser;
private readonly IDateTime _dateTime;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, ICurrentUserService currentUser, IDateTime dateTime) : base(options)
{
_currentUser = currentUser;
_dateTime = dateTime;
}
public DbSet<Transaction> Transactions { get; set; }
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<ApplicationRole> ApplicationRoles { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly);
base.OnModelCreating(builder);
builder.ApplyConfiguration(new TransactionConfigurations());
builder.ApplyConfiguration(new ApplicationUserConfigurations());
builder.ApplyConfiguration(new ApplicationUserRoleConfigurations());
builder.ApplyConfiguration(new ApplicationRoleConfigurations());
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
foreach (var item in ChangeTracker.Entries<AuditableEntity>())
{
switch (item.State)
{
case EntityState.Modified:
item.Entity.LastModifiedBy = _currentUser.UserName;
item.Entity.LastModifiedAt = _dateTime.Now;
break;
case EntityState.Added:
item.Entity.CreatedBy = _currentUser.UserName;
item.Entity.CreatedAt = _dateTime.Now;
break;
case EntityState.Deleted:
item.Entity.DeletedBy = _currentUser.UserName;
item.Entity.DeletedAt = _dateTime.Now;
item.Entity.IsDeleted = true;
break;
default:
break;
}
}
return await base.SaveChangesAsync(cancellationToken);
}
}
當我想使用 Add-Migration InitialCreate -OutputDir Persistence\Migrations創建遷移時
我收到了這個錯誤:
'ApplicationDbContext' 類型的 DbContext 無法合並,因為它沒有接受 DbContextOptions 類型的單個參數的公共構造函數或具有多個構造函數。
我該如何解決?
謝謝
您的問題是由於想要將服務注入 DbContext 引起的,這並不是一個好主意。
將其包裝起來:創建一個處理程序來處理DbContext.SavingChanges事件並在其中更新您的實體。
請參閱EFCore 中的 SaveChanges 回調? 用於其實施。
此外,假設Transactions
繼承AuditableEntity
,我不確定ChangeTracker.Entries<AuditableEntity>()
會按照您的預期進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.