[英]“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.