Linq-to-SQL:每个地址记录的 CustomerResponse 都是重复的

问题描述 投票:0回答:1

我有以下疑问:

var query = from customer in _unitOfWork.customerRepository.All()
            join adresses in _unitOfWork.AdresRepository.All() on customer.adressNo equals adresses.adressNo into adr
            from adresses in adr.DefaultIfEmpty()
            select new CustomerResponse
                       {
                           CustomerName = customer.Name
                           Select new Address
                                      {
                                          adressName = adr.name
                                          adressNo = adr.Number
                                      }
                       }

每个地址的

CustomerResponse
都是重复的。我想要的是一个具有多个地址作为子对象的
CustomerResponse

.net linq asp.net-core entity-framework-core
1个回答
0
投票

您需要对每个客户的地址进行分组,以便您可以为每个客户返回一个 CustomerResponse,并将一组地址作为子对象。您可以通过姓名来了解客户,然后将地址组合到其中

 var query = from customer in _unitOfWork.customerRepository.All()
        join address in _unitOfWork.AdresRepository.All() on customer.adressNo equals address.adressNo into adr
        from address in adr.DefaultIfEmpty()
        group address by new { customer.Name} into grouped
        select new CustomerResponse
        {
            CustomerName = grouped.Key.Name,
            Addresses = grouped
                .Where(a => a != null)
                .Select(a => new Address
                {
                    adressName = a.name,
                    adressNo = a.Number
                })
                .ToList()
        };
© www.soinside.com 2019 - 2024. All rights reserved.