Entity-Framework InvalidCastException

时间:2012-07-02 15:16:02

标签: entity-framework

此代码编译但生成运行时错误。本质上,我只是在实体框架中执行存储过程并尝试返回单个对象。关于w

的任何想法

CODE:

 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;
            }
        }

错误: 无法将类型为'System.Data.Objects.ObjectQuery`1 [TowingService2._0.Model.Towing.TowingCustomerVehicle]'的对象强制转换为'TowingService2._0.Model.Towing.TowingCustomerVehicle'。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

从我所看到的结果是ObjectQuery<TowingCustomerVehicle>类型,你需要从该查询中获得一个TowingCustomerVehicle类型的项目。最后添加First()FirstOrDefault()。之后你不需要演员。

在VS中没有试过这个,看看它是否编译但它应该可以正常工作。

希望它有所帮助。