【问题标题】:JOIN using LINQ LAMBDA使用 LINQ LAMBDA 加入
【发布时间】:2016-10-25 17:29:18
【问题描述】:

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

我正在加入带有地址的客户,如下所示:

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

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

[{"customer":{"id":1,"companyName":"Customer2","firstName":"Donald","lastName":"Trump"},"address":{"id":5,"entityId":1,"city":"Atlanta","state":"GA","zip":"33333"}},

{"customer":{"id":1,"companyName":"Customer2","firstName":"Bill","lastName":"Clinton"},"address":{"id":7,"entityId":1,"city":"Gainesville","state":"FL","zip":"33333"}},

{"customer":{"id":2,"companyName":"Customer1","firstName":"Tom","lastName":"Hanks"},"address":{"id":9,"entityId":2,"city":"Miami","state":"FL","zip":"33333"}}]

【问题讨论】:

  • 你想要GroupJoin而不是Join

标签: c# linq linq-to-sql


【解决方案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()
    };

【讨论】:

  • 效果很好。我确信下面的解决方案也有效,但这恰好是我尝试的第一个。谢谢!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2011-02-15
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多