c# - 如何使用 LINQ 批量查找/匹配和更新记录?

标签 c# .net vb.net entity-framework linq

基本上,我在数据库中有一个Items 表,其中的商品库存需要经常更新。我在 XML 提要中有更新的股票值(value)。

这并不一定意味着表格和 XML 提要中的项目数必须相同。我目前在数据库中有大约 9K 项,在 XML 中有 72K 项。

到目前为止,这是我尝试过的:

Using context As New QuotationDbContext
    For Each item In context.Items.Where(Function(i) i.Active)
        Dim matchedNode = 
            xDoc.Descendants("item").   'xDoc is an XDocument object.
                 FirstOrDefault(Function(n) n.Attribute("itemcode").Value = item.ItemNumber)
        If matchedNode IsNot Nothing Then item.Stock = matchedNode.Attribute("stock").Value
    Next
    context.SaveChanges()
End Using

..反之亦然:

Using context As New QuotationDbContext
    For Each itemNode In xDoc.Descendants("item")
        Dim itemNumber As String = itemNode.Attribute("itemcode").Value
        Dim matchedItem = context.Items.FirstOrDefault(Function(i) i.Active AndAlso
                                                                   i.ItemNumber = itemNumber)
        If matchedItem IsNot Nothing Then matchedItem.Stock = itemNode.Attribute("stock").Value
    Next
    context.SaveChanges()
End Using

问题在于,这两种方法都需要 2 分钟多一点的时间来完成“匹配和更新”,而更新所有项目需要几百毫秒,因此很明显,匹配才是花费所有时间的原因。

那么,有没有更好(更快)的方法来批量匹配/查找数据库中的记录以进行更新?

我认为我的问题的解决方案更有可能是纯 LINQ 解决方案不一定连接到 EF。不过,我想提供完整的上下文,以防万一我遗漏了什么。

P.S.虽然我的代码是在 VB 中,但也非常感谢任何使用 C# 代码的答案。

最佳答案

我认为这主要是算法问题。 您花费大量时间在 xml 中查找项目。 这里:

Dim matchedNode = 
        xDoc.Descendants("item").
             FirstOrDefault(Function(n) n.Attribute("itemcode").Value = item.ItemNumber)

例如,尝试将所有项目从您的 xml 中获取到字典中。因为字典要花 O(1) 的时间来查找元素。它会是这样的(我没有IDE来尝试这段代码):

Dim dict = xDoc.Descendants("item").ToDictionary(Function(n) n.Attribute("itemcode").Value)

Using context As New QuotationDbContext
    For Each item In context.Items.Where(Function(i) i.Active)
        If dict.ContainsKey(item.ItemNumber) Then
            item.Stock = dict(item.ItemNumber).Attribute("stock").Value
        End If
    Next
    context.SaveChanges()
End Using

关于c# - 如何使用 LINQ 批量查找/匹配和更新记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734611/

相关文章:

c# - 从其他类更新 UI 的最佳方式?

c# - wpf web 浏览器控件的限制是什么?

c# - 如何优化 Entity Framework 的添加/附加调用? (多对多插入)

c# - TransformToAncestor 给我错误的转换

c# - 监听 HTTP 请求

c# - 具有上限的线程安全集合

c# - 如何处理.NET 中已发布的公共(public)库?

vb.net - VB6 中的 Attribute 关键字有什么作用?

vb.net - 在 2 列表 vb.net 中查找不同的项目

asp.net - Gridview 将当前行与上一行进行比较