【问题标题】:Find differences between two lists in EF Core查找 EF Core 中两个列表之间的差异
【发布时间】:2020-06-17 03:45:10
【问题描述】:

我有两个列表。

客户端列表:其中一个从用户(客户端)接收

服务器列表:其中之一来自数据库。

我想在这个列表上做 3 项工作。

一:添加(如果数据不存在于服务端List中而存在于客户端List中)

二:删除数据(如果存在于服务器List中,不存在于客户端List中)

三:更新(如果服务器List和客户端Server中存在数据且数据已更改)

这是我的模型:

public class CategoryPropertyDto
{
    public Guid? Id { get; set; }
    public Guid CategoryId { get; set; }
    public string PropName { get; set; }
    public CategoryPropertyType CategoryPropertyType { get; set; }
}

客户把这个型号的列表发给我CategoryPropertyDto

现在我编写这段代码来添加数据:

var currentValue = getAllPropByCategory.Result.Select(x => new CategoryPropertyDto
            {
                CategoryId = x.CategoryId,
                CategoryPropertyType = x.CategoryPropertyType.CategoryPropertyType,
                Id = x.Id,
                PropName = x.PropName
            }).ToList();
            /// Add New Property
            var newProp = request.CategoryPropertyDtos.Where(x => x.Id == null).ToList();
            List<CategoryProperty> CategoryProperty = new List<CategoryProperty>();
            if (newProp.Count() > 0)
            {
                foreach (var item in newProp)
                {
                    CategoryProperty.Add(new CategoryProperty(item.PropName, item.CategoryPropertyType, item.CategoryId));
                }
                await unitOfWork.CategoryRepository.CategoryPropertyRepository.AddBulkCategoryProperty(CategoryProperty, cancellationToken);
            }

而且效果很好。

现在我想查找要删除的项目(存在于服务器列表中但不存在于客户端列表中)

 var removeValue = currentValue.Except(request.CategoryPropertyDtos).ToList();

但它不起作用并返回所有currentValue,我不知道如何找到要更新的项目。

我该如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    var removeValue = currentValue.Except(request.CategoryPropertyDtos).ToList();

    此行不起作用,因为在这种情况下,除了方法比较引用,而不是值,并且显然 currentValue 项与客户端项具有不同的引用。

    解决方案: 您必须在所有情况下(添加、删除、更新)都使用 ID,就像您已经为添加案例所做的那样。 因此,例如查找要删除的项目:

    var ItemIdsToDelete = currentValue.Select(p => p.Id).Except(request.CategoryPropertyDtos.Select(p => p.Id)).ToList();
    

    并使用以下方法按 id 删除项目:

    await unitOfWork.CategoryRepository.CategoryPropertyRepository.DeleteBulkCategoryPropertyById(ItemIdsToDelete, cancellationToken);
    

    您可以执行类似的操作来查找其 id 存在于客户端和服务器列表中的项目并更新它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-19
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多