asp.net核心/ EF核心多个异步请求抛出错误

时间:2016-09-15 08:12:04

标签: c# asp.net-core asp.net-core-mvc entity-framework-core

每当我对同一个控制器发出多个请求时,只有第一个请求返回数据,其余的请求会抛出错误 - 对象未设置为对象的实例。

    public async Task<List<BusinessUnit>> GetBusinessUnits(ContextUser user)
    {
        return await db.BusinessUnits.Where(x => x.Company.Id == user.SelectedCompany).Include(x => x.Company).ToListAsync();
    }

但是,如果我删除await运算符,它可以正常工作。

return db.BusinessUnits.Where(x => x.Company.Id == user.SelectedCompany).Include(x => x.Company).ToList();

Startup.cs

  services.AddDbContext<RepoDbContext>(options =>
    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

 services.AddTransient<IBusinessUnit, BusinessUnitRepository>();

EF在请求中共享相同的dbContext吗?

什么可能导致这种行为?

编辑: 这是我的dbContext类

 public class RepoDbContext : DbContext
{
    public RepoDbContext(DbContextOptions<RepoDbContext> options)
        : base(options)
    {
        Database.EnsureCreated();
    }

存储库中的dbcontext由DI注入

 RepoDbContext db;

    public BusinessUnitRepository(RepoDbContext context)
    {
        db = context;
    }

控制器:

[Route("api/[controller]/[action]")]
public class BusinessUnitAPIController : BaseController
{
    IBusinessUnit BusinessUnits;
    readonly new ContextUser User;

    public BusinessUnitAPIController(UserContextResolve userContextResolver, IBusinessUnit _BusinessUnits)
    {
        User = userContextResolver.GetUserContext;
        BusinessUnits = _BusinessUnits;
    }

    public async Task<List<BusinessUnit>> GetBusinessUnits()
    {
            var result = await BusinessUnits.GetBusinessUnits(User);
            return result;
    }

}

IBusinessUnit:

  public interface IBusinessUnit
{
    Task<List<BusinessUnit>> GetBusinessUnits(ContextUser user);
}

0 个答案:

没有答案