-1

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

代码:

 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”。

4

2 回答 2

1

选择返回一个IEnumerable<TowingCustomerVehicle>. 您需要添加.First()到 select 调用的末尾。

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();
于 2012-07-02T15:21:50.890 回答
0

据我所知,结果是 type ObjectQuery<TowingCustomerVehicle>,您需要该查询中的一项 type TowingCustomerVehicleFirst()在末尾添加或FirstOrDefault(). 之后你就不需要演员表了。

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

希望能帮助到你。

于 2012-07-02T15:23:28.253 回答