我使用 .NET 6.0 和 Blazor Server 創建了一個應用程式。有時我的應用程式中出現錯誤訊息A second operation was started on this context instance before an previous operation completed.
Blazor 服務器和 EF Core:在前一個操作完成之前,在此背景關系實體上啟動了第二個操作
我通常使用模式存盤庫。我有每個表和作業單元的存盤庫來保存和其他。在我之前的問題中向我解釋過,我使用 DbContext 不好。因為它在存盤庫和作業單元上共享 dbcontext。我閱讀了很多文章,通常的建議是僅使用自定義 DbContext。我認為這對我來說不是問題。我需要對我的框架進行一些更改,但是 np. 但我不明白一件事。我如何為每個 dbset 進行自定義通用查詢?是否有很多關于將存盤庫與背景關系工廠一起使用且沒有作業統一的文章。我真的不喜歡所有操作都是獨立的并且可以多次訪問資料庫的事實。
你的建議和經驗是什么?你有關于這方面的文章或教程嗎?
我真的只是在尋找如何使它成為“最好的”并且對我有用。非常感謝 :)
uj5u.com熱心網友回復:
DbContext的設計是短暫的。為每個操作創建一個新的背景關系實體來解決您的問題。
您的 DbContext 將是這樣的,以使其易于構建。
public class SomeDbContext : DbContext
{
private readonly IConfiguration configuration;
public SomeDbContext(IConfiguration configuration)
{
this.configuration = configuration;
// this.Database.Migrate(); <- optional
}
DbSet<SomeValue> SomeValues { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connectionString =
this.configuration.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlServer(connectionString);
}
public async ValueTask<SomeValue> InsertSomeValueAsync(SomeValue someValue)
{
using var someDbContext = new SomeDbContext(this.configuration);
EntityEntry<SomeValue> entityEntry =
await someDbContext.SomeValues.AddAsync(entity: someValue);
await someDbContext.SaveChangesAsync();
return entityEntry.Entity;
}
}
InsertSomeValueAsync 方法可以很容易地成為通用方法。
public async ValueTask<T> InsertSomeValueAsync<T>(T someValue)
where T : class
{
using var someDbContext = new SomeDbContext(this.configuration);
EntityEntry<T> entityEntry =
await someDbContext.AddAsync(someValue);
await someDbContext.SaveChangesAsync();
return entityEntry.Entity;
}
uj5u.com熱心網友回復:
一種選擇是使用 aDBContextFactory來管理背景關系。
這是我的一個應用程式中的一些示例代碼。
Program
var dbConnectionString = builder.Configuration.GetValue<string>("MyConfiguration:ConnectionString");
builder.Services.AddDbContextFactory<MySqlServerDbContext>(options => options.UseSqlServer(dbConnectionString), ServiceLifetime.Singleton);
并在(通用)資料代理中使用它:
public class ServerDataBroker
: IDataBroker
{
private IDbContextFactory<MySqlServerDbContext> _dbContextFactory;
public ServerDataBroker(IDbContextFactory<MySqlServerDbContext> factory)
=> _dbContextFactory = factory;
//.....
public async ValueTask<int> GetRecordCountAsync<TRecord>() where TRecord : class, new()
{
using var context = _dbContextFactory.CreateDbContext();
var dbSet = context.Set<TRecord>();
return dbSet is not null
? await dbSet.CountAsync()
: 0;
}
//.....
這里有一篇關于它的 MS-Docs 文章 - https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/。
在測驗中,我使用 EF InMemory - 你可以使用 Factory 與它。詢問您是否想要指向某些代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/436567.html
