让我们假设:
因此,如果我想查询具有客户主页地址街道名称的事件列表,我就去
var qry = db.Events
.Select(evt => new {
EventAddress =
evt.Client
.Addresses
.FirstOrDefault(a => a.AddressType.Equals("HOME")).StreetName
});
但是,如果我想获得完整地址,我需要连接sereval地址字段。目前我正在尝试像
这样的东西var qry = db.Events
.Select(evt => new {
EventAddress =
evt.Client
.Addresses
.FirstOrDefault(a => a.AddressType.Equals("HOME")).StreetNo + " " +
evt.Client
.Addresses
.FirstOrDefault(a => a.AddressType.Equals("HOME")).StreetName + " " +
evt.Client
.Addresses
.FirstOrDefault(a => a.AddressType.Equals("HOME")).City
});
它不起作用,看起来也很难看
有没有更好的方法来制作
evt.Client.Addresses.FirstOrDefault(a => a.AddressType.Equals("HOME"))
"可重复使用"所以我可以去
var qry =
db.Events
.Select(evt => new {
EventAddress =
STUFF.StreetNo + " " + STUFF.StreetName + " " + STUFF.City
});
非常感谢提前!
休
更新
感谢Ilian的答案,它运作良好。并基于此我创建了答案的扩展版本
var qry =
db.Events
.Select(evt => new {
EventAddress =
db.Addresses.Select(a => new
{
ClientId = a.ClientId,
AddressType = a.AddressType,
FullAddress = (a.addStreetNo ?? "") + (a.addStreetName ?? "")
})
.FirstOrDefault(a => a.ClientId == e.Client.ClientId && a.AddressType.Equals("HOME"))
.FullAddress
});
答案 0 :(得分:0)
使用查询语法:
var qry =
from evt in db.Events
let firstAddress = evt.Client.Addresses.FirstOrDefault(a => a.AddressType.Equals("HOME"))
where firstAddress != null
select new
{
EventAddress = firstAddress.StreetNo + " " +
firstAddress.StreetName + " " +
firstAddress.City
}