在上一个操作完成之前,第二个操作在此上下文中启动。不保证任何实例成员都是线程安全的

A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe

您好,当我在一个方法中两次访问通用存储库的相同方法时出现此错误。

var polyTables = _vehicleService.GetAll().ToList()
                    .Select(p => new PolyTable
                     {
                         VinNumber = p.ChassisNumber ?? "-",
                         BrandName = p.BrandName,
                         FirstRegisterDate = p.FirstRegistrationDate,
                         ModelCode = p.ModelCode,
                         Plate = p.Plate ?? "-",
                         CreatedBy = 1,
                         IsActive = true,
                         AuthorizedServiceId = p.AuthorizedServiceId,
                         Customer = GetLastCustomerName(p.Id, periodicCodes)
                     }).ToList();

Heres My Error

 private string GetLastCustomerName(string vehicleId,IEnumerable<PeriodicCode> periodicCodes)
        {
            var invoices = _invoiceService.GetByVehicle(vehicleId);
            var lastInvoiceLine = _invoiceLineService.GetLastInvoiceLineByInvoices(invoices, periodicCodes);
            var customer =new Customer();
            if (lastInvoiceLine != null )
            customer = _customerService.GetById(lastInvoiceLine.CustomerNumber);

            return customer.Name + " " + customer.SurName;
        }

这是我的通用存储库方法

 public IEnumerable<T> Find(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)
    {
        if (includes == null)
            return Context.Set<T>().Where(predicate);
        else
            return includes.Aggregate(Context.Set<T>().Where(predicate).AsQueryable(), (current, includeProperty) => current.Include(includeProperty));
    }

这里是 GetByVehicle 方法

public IEnumerable<Invoice> GetByVehicle(string vehicleId) =>
    _genericRepository.Find(s => s.VehicleId == vehicleId);

我通过将 IEnumerable 更改为在此处列出来修复此问题

public InvoiceLine GetLastInvoiceLineByInvoices(List<Invoice> invoices, List<InvoiceLine> invoiceLine)
{
    if (invoices != null)
    {
       return invoiceLine.Where(s => s.WorkmanshipId != null && invoices.Select(p=> p.Id).Contains(s.InvoiceId) ).OrderByDescending(s=> s.InvoiceDate).FirstOrDefault();
    }
    return null;
}

Maartens 的评论帮了大忙。