0

我要做的是从我的数据库中获取特定值并将其解析到视图中以将其显示在表中。我遇到了与传递到字典中的模型项的类型相同的问题.... {Models.App} 但我传递的是 {Models.App, System.Double}并尝试以类似的方式解决我的问题。所以基本上我在模型中创建了一个类:

 public Vehicle manur_name {get; set;}
 public Vehicle manur_date { get; set; }
 public Vehicle daily_hire_rate { get; set; }

但是当我在 linq 查询的控制器中使用它时,它给了我和错误。

 var s = from veh in db.Vehicles
 join c in db.VehicleCategories on veh.vehicle_category_code equals  c.
 join m in db.Models on veh.model_code equals m.model_code
 join man in db.Manufacturers on veh.manufacturer_code equals man.manufacturer_code
 where c.vehicle_category_description == cat && m.body_style == b                         
            select new CarClass {
                          manur_name = man.manufacturer_name, 
                          manur_date = m.model_code, 
                          daily_hire_rate = veh.daily_hire_rate};

它给了我错误:

错误:无法将“十进制”类型隐式转换为“carRentalMVC.Models.Vehicle” 无法将“字符串”类型隐式转换为“carRentalMVC.Models.Vehicle” 无法将“字符串”类型隐式转换为“carRentalMVC.Models.Vehicle”

这是解决问题后我在控制器中的内容:

        CarRentalDatabaseDataContext db = new CarRentalDatabaseDataContext();
    public ActionResult Index(String cat, String b, String sort)
    {
        String day_hire = "Daily hire rate";
        String man_date = "Manufacturing date";
        string man_n = "Manufacturer's name";

        var s = db.Vehicles.Where(c => c.Model.body_style == b)
             .Select(u => new CarClassViewModel { 
                 manur_name = u.Manufacturer.manufacturer_name, 
                 model_code = u.model_code,
                 daily_hire_rate = u.daily_hire_rate,
                 manur_date = u.manufacturing_date
             })
             .Distinct(); //I don't need repeating data

        //this is for sorting them, but I haven't implemented this in the view yet. 
        if (sort == man_n){s = s.OrderBy(c=>c.manur_name);}
        else if (sort == man_date){s = s.OrderBy(c =>c.manur_date);}
        else if (sort == day_hire){s = s.OrderBy(c => c.daily_hire_rate);}
        else{s = s.OrderBy(c => c.daily_hire_rate);}

        var v = s.Select(u => new CarClassViewModel
        {
            manur_name = u.manur_date,
            model_code = u.model_code,
            daily_hire_rate = u.daily_hire_rate,
        }); //this is for returning values I need

        return View(v); //I've tried View(v.ToList()) as well
    }

现在这会在我的表中返回空行。我不为该方法解析数据是否重要?

4

1 回答 1

4

我不确定我做错了什么。

您的数据模型非常混乱。即使将命名约定放在一边,查看您的属性:

public Vehicle manur_name {get; set;}
public Vehicle manur_date { get; set; }
public Vehicle daily_hire_rate { get; set; }

汽车的制造商名称不是车辆 - 它可能是一个字符串。汽车的制造日期不是车辆 - 它可能是DateTime. 汽车的每日租金不是车辆 - 它可能是decimal. 所以你的模型应该是这样的:

public string ManufacturerName { get; set; }
public DateTime ManufacturingDate { get; set; }
public decimal DailyHireRate { get; set; }

让您的数据模型正确,其他一切都应该变得简单得多。话虽如此,这看起来也很可疑:

manur_date = m.model_code

A "date" and a "code" don't sound like the same thing to me.

于 2012-09-22T06:50:44.970 回答