Click here to Skip to main content
15,888,270 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 layers in my web app. 1. is business layer with domain models and context classes for each model. 2. is user layer with view models, and it should be with controllers and views.
My task is to make CRUD over domain models but also over view models. So I've got 2 context classes (one in first layer and second in second layer) that is error.
How can I make CRUD over both models (domain and viewmodels) without having two context classes?
When I make a controller with contextClass from domain model I've got an error --> show you below in controller 'details, edit and delete actionResult'

E.g.
C#
//domain model
Public class Car:ICar
{
[Key]
public int I'd{get; set;}
public string Name{get; set}
}

//viewModel
Public class ViewCar:Car
{
[Display(Name="Cars model")]
public string Name{get; set;}
}

//controller
public ActionResult Details(int? I'd)
{
if(id==null)
{return new HttpStatusCodeResult(HttpStatusCode.BadRequest);}
ViewCar viewCar=db.Cars.Find(id);
if(viewCar==null)
{return HttpNotFound();}
return View (viewCar);
}

Error is in line where I need to find by id and it's says
C#
"Cannot implicitly convert type 'Project.Services.Car' to 'Project.MVC.ViewModels.ViewCar'. An explicit conversion exists (are you missing a cast?)"


My another question is how can I cast one project to another?

What I have tried:

I have read all over internet and there's are similar answers from int to string and so on but I didn't find any examples from casting one project to another. So please if someone can give me an explanation on how I can do that cast? And how to make CRUD over models in business layer and over viewModels in users layer and with one contextClass (how it should be in the first place)?
Posted
Updated 20-Jan-20 23:13pm
v2

1 solution

The short answer is that you can't\shouldn't. Your view models are not database entities, they are models that contain the data the page needs to render. Sometimes there will indeed be a one-to-one relationship between your view model and your database model, especially for simple data and pages, but that exception doesn't make the rule.

Keep your data models and your view models separate. If there is a lot of commonality between a data model and a view model then use an auto mapper (such as automapper, google for it) to "convert" between the data model and view model and vice versa.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900