有没有办法简化具有多对一关系的Linq查询?

时间:2014-05-27 20:41:12

标签: c# linq

我正在使用Linq实体来查询具有0到4个街道地址的联系人记录。我想要获得的地址是地址类型为" Primary"的地址。此查询获取我想要的信息并将其返回到一个数组,该数组从JSON方法传递到我的前端。

 var data = db.Contacts
            .Where(a => a.LastName.Contains(term))
            .Select(r => new
            {
                r.Id,
                value = r.LastName + ", " + r.FirstName + " " + r.MiddleName,
                r.Email,
                r.Title,
                Street1 = c.Addresses
                    .Where(a => a.AddressType.Name.Contains("Primary"))
                    .FirstOrDefault().Street1
                ,
                Street2 = c.Addresses
                    .Where(a => a.AddressType.Name.Contains("Primary"))
                    .FirstOrDefault().Street2
                ,
                City = c.Addresses
                    .Where(a => a.AddressType.Name.Contains("Primary"))
                    .FirstOrDefault().City
                ,
                State = c.Addresses
                    .Where(a => a.AddressType.Name.Contains("Primary"))
                    .FirstOrDefault().State
                ,
                Postal = c.Addresses
                    .Where(a => a.AddressType.Name.Contains("Primary"))
                    .FirstOrDefault().PostalCode
                ,
                r.Institution.Name
            })
            .Take(10).ToArray();

我想知道的是,是否有办法简化查询部分 **。其中(a => a.AddressType.Name.Contains(" Primary"))**这样我每次都不会重复相同的部分?

1 个答案:

答案 0 :(得分:5)

您可以使用let关键字:

from a in db.Contacts
where a.LastName.Contains(term)
let primaryAddress = a.Addresses
                    .Where(a => a.AddressType.Name.Contains("Primary"))
                    .FirstOrDefault()
select new 
{
    a.Id,
    value = a.LastName + ", " + a.FirstName + " " + a.MiddleName,
    a.Email,
    a.Title,
    Street1 = primaryAddress.Street1,
    Street2 = primaryAddress.Street2,
    City = primaryAddress.City,
    State = primaryAddress.State,
    Postal = primaryAddress.PostalCode,
    a.Institution.Name
})

这是我更喜欢全面的语法到流畅语法的情况之一,因为它产生了更好的可读代码。在引擎盖下,它被转换为流畅的语法,带有两个Select s:

db.Contacts
    .Where(a => a.LastName.Contains(term))
    .Select(a => 
    new 
    { 
        a = a,
        primaryAddress = 
            a.Addresses
                .FirstOrDefault(a => a.AddressType.Name.Contains("Primary"))
    })
    .Select(a =>
    new 
    {
        a.a.Id,
        value = a.a.LastName + ", " + a.a.FirstName + " " + a.a.MiddleName,
        a.a.Email,
        a.a.Title,
        Street1 = a.primaryAddress.Street1,
        Street2 = a.primaryAddress.Street2,
        City = a.primaryAddress.City,
        State = a.primaryAddress.State,
        Postal = a.primaryAddress.PostalCode,
        a.a.Institution.Name
    })

接受你的选择!