从IQueryable查询中返回一条记录
本文关键字:一条 记录 返回 IQueryable 查询 | 更新日期: 2023-09-27 18:02:11
大家好,我有这个查询
public IQueryable<HeaderMRC> ShowHeader(int MRCId)
{
return from m in _ctx.MaterialRequestContractorDetails
where m.MaterialRequestContractorId == MRCId
join materialRequestContractor in _ctx.MaterialRequestContractors on m.MaterialRequestContractorId equals materialRequestContractor.Id
join mat in _ctx.MaterialDescriptions on m.MaterialDescriptionId equals mat.Id
join l in _ctx.Lines on m.LineId equals l.Id
join s in _ctx.Sheets on l.Id equals s.LineId
select new HeaderMRC()
{
Code = materialRequestContractor.Code,
UnitArea = l.Unit,
LineType = l.Type,
RequestDate = materialRequestContractor.RequestDate
};
}
这个查询产生多个记录,但我只需要第一个,我怎么能返回第一个值作为IQueryable
只需添加.First()
或.FirstOrDefault()
return (from m in _ctx.MaterialRequestContractorDetails
where m.MaterialRequestContractorId == MRCId
join materialRequestContractor in _ctx.MaterialRequestContractors on m.MaterialRequestContractorId equals materialRequestContractor.Id
join mat in _ctx.MaterialDescriptions on m.MaterialDescriptionId equals mat.Id
join l in _ctx.Lines on m.LineId equals l.Id
join s in _ctx.Sheets on l.Id equals s.LineId
select new HeaderMRC()
{
Code = materialRequestContractor.Code,
UnitArea = l.Unit,
LineType = l.Type,
RequestDate = materialRequestContractor.RequestDate
}).FirstOrDefault();
或
return (from m in _ctx.MaterialRequestContractorDetails
where m.MaterialRequestContractorId == MRCId
join materialRequestContractor in _ctx.MaterialRequestContractors on m.MaterialRequestContractorId equals materialRequestContractor.Id
join mat in _ctx.MaterialDescriptions on m.MaterialDescriptionId equals mat.Id
join l in _ctx.Lines on m.LineId equals l.Id
join s in _ctx.Sheets on l.Id equals s.LineId
select new HeaderMRC()
{
Code = materialRequestContractor.Code,
UnitArea = l.Unit,
LineType = l.Type,
RequestDate = materialRequestContractor.RequestDate
}).First();
FirstOrDefault
将返回第一个,或者如果没有Default(T)
(通常为null),如果它是一个类对象…
所以要把它作为IQueryable
,这对我来说似乎不像这样做:
return new List<HeaderMRC> { (from m in _ctx.MaterialRequestContractorDetails
where m.MaterialRequestContractorId == MRCId
join materialRequestContractor in _ctx.MaterialRequestContractors on m.MaterialRequestContractorId equals materialRequestContractor.Id
join mat in _ctx.MaterialDescriptions on m.MaterialDescriptionId equals mat.Id
join l in _ctx.Lines on m.LineId equals l.Id
join s in _ctx.Sheets on l.Id equals s.LineId
select new HeaderMRC()
{
Code = materialRequestContractor.Code,
UnitArea = l.Unit,
LineType = l.Type,
RequestDate = materialRequestContractor.RequestDate
}).FirstOrDefault() }.AsQueryable();
只需将您的查询包含在()
中并附加Take(1)
,这是FirstOrDefault
的集合等效:
return (from m in ...
...
...).Take(1);