使用LINQ LAMBDA加入

时间:2016-10-25 03:29:24

标签: c# linq linq-to-sql

我正在尝试使用他们的地址获取客户列表。在我的数据库中,Customer1有1个地址,而Customer2有2个地址。

我正在通过地址加入客户,就像这样:

app

我希望结果是2个客户,每个客户都嵌套了地址。相反,我得到3条记录(每个地址的记录),如下所示。有谁知道如何调整我的查询以获得我正在寻找的结果?谢谢!

var customers = _dbContext.Customer.Join(_dbContext.Address, c => c.Id, a => a.EntityId, (c, a) => new { Customer = c, Address = a });

2 个答案:

答案 0 :(得分:1)

尝试以下代码

var customers = _dbContext.Customer
    .GroupJoin(
        _dbContext.Address,
        c => c.Id,
        a => a.EntityId,
        (c, a) => new
        {
            c.Id,
            c.CompanyName,
            c.FirstName,
            c.LastName,                        
            Address = a.ToList()
        }
    );

或使用查询样式

var customers = from c in _dbContext.Customer
    join a in _dbContext.Address on c.Id equals a.EntityId into g
    select new
    {
        c.Id,
        c.CompanyName,
        c.FirstName,
        c.LastName,
        Address = g.ToList()
    };

答案 1 :(得分:0)

这将解决您的问题。您需要对客户进行分组并循环访问每个客户的地址。

var customers = _dbContext.Customer
                    .Join(_dbContext.Address
                    , c => c.Id
                    , a => a.EntityId, (c, a) => new {  c.Id, Address = a }).GroupBy(j => j.Id);

                foreach (var customer in customers)
                {
                    Console.WriteLine($"Customer :{customer.Key} , Address : { customer.Count() }");
                    foreach (var Addr in customer)
                    {
                        Console.WriteLine(Addr.xxxx);
                    }
                }