在下面的Linq to Entities查询中,如果查询返回0个OfficeTelephone对象,我需要在返回值的x.Number中放置一个默认值。我试过了 x.Number ??" 555-1212"但这会引发错误。
from c in Contacts
.Where(a => a.LastName.Contains("ANDUS")).Take(10)
select new
{
Id = c.Id,
OfficeTelephone = c.Telephones.Where(a=>a.TelephoneType.Name.Contains("Office")).Select(x => new { x.AreaCode, x.Number, x.TelephoneType, x.Primary })
}
我尝试过类似的事情:
from c in Contacts
.Where(a => a.LastName.Contains("ANDUS")).Take(10)
select new
{
Id = c.Id,
OfficeTelephone = c.Telephones
.Where(a=>a.TelephoneType.Name.Contains("Office"))
.Select(x => new { x.AreaCode, x.Number, x.TelephoneType, x.Primary })
.DefaultIfEmpty()}
但我不确定如何将默认对象推入DefaultIFEmpty()
答案 0 :(得分:0)
使用DefaultIfEmpty
并传递一个默认实例,其中包含默认情况下您想要的值,即如果没有返回任何行。
尝试这样:
Contacts.Where(a=>a.LastName.Contains("ANDUS"))
.Take(10)
.Select(x => new
{
Id = x.Id,
OfficeTelephone = x.Telephones
.Where(a=> a.Telephone.Name.Contains("Office"))
.Select(b=> new Telephone
{
b.AreaCode,
b.Number,
b.TelephoneType,
b.Primary
})
.DefaultIfEmpty(new Telephone())
});
我假设typeof(x.Telephones) == typeof(List<Telephone>)