Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将一个项目强制转换为另一个项目(“无法将类型';Project.Services…';隐式转换为';Project.MVC…&”)_C#_Asp.net Mvc_Casting - Fatal编程技术网

C# 如何将一个项目强制转换为另一个项目(“无法将类型';Project.Services…';隐式转换为';Project.MVC…&”)

C# 如何将一个项目强制转换为另一个项目(“无法将类型';Project.Services…';隐式转换为';Project.MVC…&”),c#,asp.net-mvc,casting,C#,Asp.net Mvc,Casting,这是我的控制器出错的地方 `// GET: MakeViewModels/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } MakeViewModel makeViewModel = db

这是我的控制器出错的地方

`// GET: MakeViewModels/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        MakeViewModel makeViewModel = db.VehicleMakes.Find(id); 

        if (makeViewModel == null)
        {
            return HttpNotFound();
        }
        return View(makeViewModel);
   }`
错误为…db.VehicleMakes.Find(id)

编辑和删除ActionResult中也存在相同的错误

这是我在namespace Project.MVC中的视图模型

 public class MakeViewModel: VehicleMake
{

    [Required(ErrorMessage ="Required field")]
    [StringLength(100, MinimumLength =2)]
    [Display(Name ="Name")]
    public new string VehicleMakeName { get; set; }

    [Required(ErrorMessage ="Required data")]
    [DataType(DataType.MultilineText)]
    [Display(Name ="Description")]
    public new string VehicleMakeAbrv { get; set; }
}
我的域模型在名称空间项目中。它的服务包含VehicleMakeID(Key)和上面的所有代码

错误

CS0266无法隐式转换类型“Project.Services.VehicleMake” 到“Project.MVC.ViewModels.MakeViewModel”。显式转换 存在(您是否缺少演员阵容?)


现在,有人能告诉我如何解决这个问题吗,因为我找不到解决方案。

您不能隐式地将父对象转换为子对象

var v = db.VehicleMakes.Find(id); //this is of type VehicleMakes

var newMakeViewModel = new MakeViewModel 
{
  VehicleMakeName = v.VehicleMakeName,
  VehicleMakeAbrv = v.VehicleMakeAbrv 
};

你也可以看看显式的父母对孩子的角色转换,但我更喜欢这样

太棒了!把它作为后代的答案:)我是新来的,所以感谢你的建议。再次感谢您不要使用这行代码“MakeViewModel MakeViewModel=db.VehicleMakes.Find(id)”,我只是把您的代码放在这里,它就可以工作了