如何在Linq查询中的.Select中调用方法而不必编写两次select?

时间:2018-11-08 11:28:13

标签: c# asp.net .net linq

以下是我的代码。但是正如您所看到的,我必须写两次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();

是否可以执行相同操作而不必两次写选择?在某些情况下,可能会有十几个属性。我不想使我的代码不必要地冗长。

1 个答案:

答案 0 :(得分:1)

可能不会转换为基础数据库,因此您基本上需要编写两次。但是,您可以在使用方法语法之后使用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();