从联接linq语句中选择视图模型列表
本文关键字:选择 视图 模型 列表 语句 linq | 更新日期: 2023-09-27 18:08:45
我在linq
语句中有一个简单的连接
var events = (from e in context.Events
join o in context.Offices on e.OfficeId equals o.Id
where e.StartDate >= DateTime.Now
select e)
.AsEnumerable()
.Select(x => new vm_Events()
{
Cost = x.Cost,
StartDate = x.StartDate,
EndDate = x.EndDate.HasValue ? (x.EndDate).Value : new DateTime(),
Address = x.Address,
Image = x.SupportingImage,
Info = x.Info,
Name = x.Name,
LocationName = x.LocationName,
Office =
string.Format("For more information please call the {0} office at {1}", x.Offices.Name,
x.Offices.PhoneNumber),
StateZip = string.Format("{0}, {1}, {2}", x.City, x.State, x.Zip)
}).ToList();
查询构建得很好,但是当我包含连接的offices
表时,给了我空引用。在呼叫.AsEnumerable()
之前,我是否需要将select e
更改为其他内容?
我已经验证了我在office表上查找的数据不为空
如果没有延迟加载,则无法在AsEnumerable
之后访问x.Offices.Name
。我建议你分两步:
- 在匿名类中加载所有需要的数据 构建vm_Events对象
var events = (from e in context.Events
join o in context.Offices on e.OfficeId equals o.Id
where e.StartDate >= DateTime.Now
select e)
.Select(x => new
{
Cost = x.Cost,
StartDate = x.StartDate,
EndDate = x.EndDate.HasValue ? (x.EndDate).Value : new DateTime(),
Address = x.Address,
Image = x.SupportingImage,
Info = x.Info,
Name = x.Name,
LocationName = x.LocationName,
OfficeName = x.Offices.Name,
OfficePhoneNumber = x.Offices.PhoneNumber,
x.City,
x.State,
x.Zip
}).ToList()
.Select(x=> new vm_Events
{
Cost = x.Cost,
StartDate = x.StartDate,
EndDate = x.EndDate,
Address = x.Address,
Image = x.SupportingImage,
Info = x.Info,
Name = x.Name,
LocationName = x.LocationName,
Office = string.Format("For more information please call the {0} office at {1}", x.OfficeName, x.OfficePhoneNumber),
StateZip = string.Format("{0}, {1}, {2}", x.City, x.State, x.Zip)
}).ToList();