在创建模型时不能使用上下文。 EF-Core ASP.net Core2.2

问题描述 投票:0回答:1

我看过很多帖子都在谈论这个问题,但没有一个帖子解决了我的问题

场景数据库层与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; }



}

出现错误的管理器

 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;
    }

如果我刷新数据将显示的页面,则第一次出现错误并且网格不显示数据

我做错了什么

这是我使用Building An ASP.NET Core Application With Web API And Code First Development的教程

谢谢您的帮助

c# asp.net asp.net-core .net-core entity-framework-core
1个回答
0
投票

你已经陷入了一个经典的情况,你在这个环境中保持了很长时间。

因为NationalityManager被注册为单身,所以您的上下文被注册为瞬态并不重要。将寿命短的东西注入具有长寿命的东西中有效意味着寿命缩短的寿命延长了寿命。

你可以让你的经理对象缩短,或者你可以将context factory注入你的经理。上下文工厂确保在需要时创建您的(应该是短暂的)上下文。

当您同时进行API调用时,它们会尝试同时使用非线程安全上下文。第一个调用是设置模型,然后是另一个想要在设置时使用模型的调用。

在EF Core之前,我使用原始EF为.NET Framework设计的addressed this issue。它可能会给你更多背景知识。

© www.soinside.com 2019 - 2024. All rights reserved.