[英]“Context cannot be used while the model is being created” using ASP.NET Core Console Application With EF 6
[英]The context cannot be used while the model is being created. EF-Core ASP.net Core2.2
我看過很多關於這個問題的文章,但是都沒有解決我的問題
API控制器IDataRepository DataManagers的場景數據庫層
碼
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:LawyerApplicationDB"]), ServiceLifetime.Transient);
services.AddSingleton(typeof(IDataRepository<Clients, long>), typeof(ClientManager));
services.AddSingleton(typeof(IDataRepository<Nationality, long>), typeof(NationalityManager));
services.AddMvc();
}
的ApplicationContext
public class ApplicationContext: DbContext
{
public ApplicationContext(DbContextOptions opts) : base(opts)
{
}
public DbSet<Clients> Clients { get; set; }
public DbSet<Nationality> Nationalities { get; set; }
}
出現錯誤的Manager
public class NationalityManager : IDataRepository<Nationality, long>
{
private ApplicationContext ctx; //not static
public NationalityManager(ApplicationContext c)
{
ctx = c;
}
public Nationality Get(long id)
{
var nationality = ctx.Nationalities.FirstOrDefault(b => b.Id == id);
return nationality;
}
public IEnumerable<Nationality> GetAll()
{
var nationalities = ctx.Nationalities.ToList();
return nationalities;
}
該錯誤首次出現,並且如果我刷新數據將顯示的頁面,網格將不會顯示數據
我做錯了
這是我使用Web API和Code First開發構建ASP.NET Core應用程序的教程
謝謝您的幫助
您陷入了一種經典情況,即保持上下文的時間過長。
因為NationalityManager
已注冊為單例,所以您的上下文已注冊為瞬態也沒關系。 生命周期短的事物有效地注入了生命周期較長的事物,這意味着生命周期較短的事物的壽命會延長。
您可以縮短經理對象的壽命,也可以將上下文工廠注入經理。 上下文工廠確保在需要時創建您的(應該是短暫的)上下文。
當同時有API調用進入時,它們將嘗試同時使用非線程安全上下文。 第一個調用是建立模型,然后是另一個調用,它想在建立模型時使用模型。
在使用EF Core之前,我已經使用為.NET Framework設計的原始EF 解決了這個問題 。 它可能會為您提供更多背景知識。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.