Sql – ASP.NET MVC 2 LINQ-to-SQL generated classes and Model Validation

asp.netasp.net-mvclinq-to-sqlmodel

I just want to make sure I understand correctly the best practices for ASP.NET MVC2 with LINQ-TO-SQL.

Please correct me if I am wrong at any of the following points:

  • LINQ TO SQL generates classes for
    you, based on your tables
  • The generated classes are Models
  • Those are the models we are supposed to use in the Views
  • If we want to add validation to the models, we extend the partial class and set data
    annotations. Something like
    this.

Generally my question is about the data validation. What I used to do is create a "shadow" Model for each of my LINQ-to-SQL generated classes and put the data validation there. Then, in the controllers I was creating an instance of the "shadow" model and also retrieve data (using Repository pattern). Mapped from the entity to the shadow model and passed it to the view. So, something like that (in the Controller):

// Car is class generated by LINQ-to-SQL, based on the Car table
// Use repository class to retrieve the data (Car)
Car car = myDatabaseRepository.GetCar(1);

// CarModel is my 'shadow' model, which has all the data validation.
// For example, it makes sure Year is before 2010 (let's say).
CarModel carModel = new CarModel();
carModel.Year = car.Year;
carModel.Make = car.Make;
carModel.Model = car.Model;

return View(carModel);

This is wrong, right (no pun intended)? It should have been only:

// Car should have been extended (as partial) and data annotation
// should have been in the extended class, rather than a whole separate
// model class.
Car car = myDatabaseRepository.GetCar(1);
return View(car);

Right?

Best Answer

I think it is a best practice to have a ViewModel (what you termed "shadow" model) that is used to pass only relevant data model information to a view and incorporating UI validation metadata. You can also use a library such as AutoMapper to copy over the values, rather than coding each one by hand.

A Table = Model approach can work in very simple scenarios (few tables + simple UI exactly matching database schema). In order to save yourself a lot of pain later on it is recommended to use ViewModels.