[英]How to call a method within .Select in Linq query without having to write select twice?
The following is my code that works.以下是我的工作代码。 But as you can see I am having to write select twice
但正如你所看到的,我不得不写两次 select
var lstCargoRequestVM =
(from c in db.Cargo
join v in db.Vehicles on c.VehicleID equals v.VehicleID
join cmp in db.Companies on c.CompanyID equals cmp.CompanyID
where c.Isdeleted == false && c.IsActive == true
select new CargoRequestVM
{
CargoId = c.CargoID,
CompanyName = cmp.CompanyName,
VehicleNo = v.VehicleNo,
Date = c.DateOfPassage,
Type = c.Type.ToString()
})
.AsEnumerable()
.Select(x => new CargoRequestVM
{
CargoId = x.CargoId,
CompanyName = x.CompanyName,
VehicleNo = x.VehicleNo,
Date = x.Date,
Type = CargoElements.CargoTypeName(x.Type.ToString())
}).ToList();
Is it possible to do the same without having to write select twice?是否可以在不必编写 select 两次的情况下执行相同操作? There could be more than a dozen properties in certain case.
在某些情况下,可能有十几个属性。 I don't want to make my code unnecessarily lengthy.
我不想让我的代码不必要地冗长。
Probably that wouldn't have a translation to underlying database and thus you need to write basically twice.可能不会翻译到底层数据库,因此您基本上需要编写两次。 However you can apply the AsEnumerable() after where using method syntax like (assuming you in fact have a good relational schema defined and navigational properties set - in Linq you very rarely need join keyword):
但是,您可以在 where 使用方法语法之后应用 AsEnumerable() (假设您实际上定义了良好的关系模式并设置了导航属性 - 在 Linq 中,您很少需要 join 关键字):
stVM = db.Cargo
.Include( c => c.Vehicle )
.Include( c => c.Company )
.Where( c => !c.Isdeleted && c.IsActive )
.AsEnumerable()
.Select( c => new CargoRequestVM
{
CargoId = c.CargoID,
CompanyName = c.Company.CompanyName,
VehicleNo = c.Vehicle.VehicleNo,
Date = c.DateOfPassage,
Type = CargoElements.CargoTypeName(c.Type.ToString())
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.