【问题标题】:A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe在前一个操作完成之前,第二个操作在此上下文中开始。不保证任何实例成员都是线程安全的
【发布时间】:2018-10-03 08:45:39
【问题描述】:

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

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

Heres GetByVehicle 方法

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

【问题讨论】:

  • 您不只是执行单个查询。从 SQL 查询读取结果时,您正在执行 SQL 查询并在内存中执行操作。在内存中,您正在执行另一个 SQL 查询,这在同一个连接中是不允许的。
  • 在您的 GetLastCustomerName 方法中尝试:var invoices = _invoiceService.GetByVehicle(vehicleId).ToArray();。您在 GetLastInvoiceLineByInvoices 方法调用中使用发票(目前是查询,而不是结果)作为参数。
  • 试过 ToArray 还是一样的错误

标签: c# ef-core-2.1


【解决方案1】:

我通过将 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 的评论帮助很大。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2020-01-22
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多