0

This is the place where I get an error in my controller

`// 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);
   }`

Error is ....db.VehicleMakes.Find(id)

The same error is also in Edit and Delete ActionResult.

This is my view Model in 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; }
}

My domain model is in namespace Project.Services it`s contains VehicleMakeID(Key) and all code above.

Error

CS0266 Cannot implicitly convert type 'Project.Services.VehicleMake' to 'Project.MVC.ViewModels.MakeViewModel'. An explicit conversion exists (are you missing a cast?)

Now, can someone tell me how to fix this because I can't find solution?

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
Katy
  • 5
  • 1
  • 2

1 Answers1

0

You cannot implicitly convert the parent to the child.

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

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

You can take a look at explicit parent to child casting as well but I prefer this. Unable to Cast from Parent Class to Child Class

LinkedListT
  • 681
  • 8
  • 24
  • 1
    I'm new so appreciate your advice. Thanks again – Katy Jan 22 '20 at 15:04
  • 1
    Instead of this line ' MakeViewModel makeViewModel=db.VehicleMakes.Find(id)' I just put your piece of code and it's works – Katy Jan 22 '20 at 15:08