2012-07-02 104 views
-1

此代碼編譯但生成運行時錯誤。實質上,我只是在實體框架中執行一個存儲過程並嘗試返回一個對象。實體框架InvalidCastException

public static TowingCustomerVehicle GetTowingCustomerVehicle(int vehicleID) 
     { 
      using (ProductServiceEntities context = new ProductServiceEntities()) 
      { 
       TowingCustomerVehicle vehicle = (TowingCustomerVehicle)context.Vehicles 
         .Where(v => v.VehiclePK == vehicleID) 
         .Select(v => new TowingService2._0.Model.Towing.TowingCustomerVehicle 
         { 
          CurbWeight = (int)v.CurbWeight, 
          HitchSystemRating = (int)v.TowingCapacityMaximum, 
          FuelType = v.FuelType, 
          TopType = v.TopType, 
          TongueLoadRating = (v.TowingCapacityMaximum ?? 0), 
          IsCVT = v.IsAutoTransCVT ?? false, 
          DriveType = v.Driveline, 
          EPAClass = v.EPAClass, 
          Make = v.Make, 
          Model = v.Model 
         }); 

       vehicle.AttachedWiring = context.IsAttachedWiring(vehicleID).Count() > 0 ? true : false; 


       return vehicle; 
      } 
     } 

ERROR: 無法轉換類型的對象 'System.Data.Objects.ObjectQuery`1 [TowingService2._0.Model.Towing.TowingCustomerVehicle]' 上鍵入瓦特

CODE任何想法'TowingService2._0.Model.Towing.TowingCustomerVehicle'。

回答

1

選擇返回IEnumerable<TowingCustomerVehicle>。您需要將.First()添加到選擇呼叫的末尾。

TowingCustomerVehicle vehicle = context.Vehicles 
        .Where(v => v.VehiclePK == vehicleID) 
        .Select(v => new TowingService2._0.Model.Towing.TowingCustomerVehicle 
        { 
         CurbWeight = (int)v.CurbWeight, 
         HitchSystemRating = (int)v.TowingCapacityMaximum, 
         FuelType = v.FuelType, 
         TopType = v.TopType, 
         TongueLoadRating = (v.TowingCapacityMaximum ?? 0), 
         IsCVT = v.IsAutoTransCVT ?? false, 
         DriveType = v.Driveline, 
         EPAClass = v.EPAClass, 
         Make = v.Make, 
         Model = v.Model 
        }).First(); 
0

從我可以RHE結果看到的是ObjectQuery<TowingCustomerVehicle>型的,並從該查詢需要TowingCustomerVehicle類型的一個項目。在末尾添加First()FirstOrDefault()。之後你不需要演員。

在VS中沒有嘗試過,看看它是否編譯,但它應該工作正常。

希望它有幫助。