title: ASP.NET MVC 2 LINQ-to-SQL generated classes and Model Validation
body: <p>I just want to make sure I understand correctly the best practices for ASP.NET MVC2 with LINQ-TO-SQL.</p>
  
  <p>Please correct me if I am wrong at any of the following points:</p>
  
  <ul>
  <li>LINQ TO SQL generates classes for
  you, based on your tables</li>
  <li>The generated classes are Models</li>
  <li>Those are the models we are supposed to use in the Views</li>
  <li><strong>If we want to add validation to the models, we extend the partial class and set data
  annotations. Something like</strong> <a href="http://www.asp.net/learn/mvc/tutorial-39-cs.aspx" rel="nofollow noreferrer">this</a>.</li>
  </ul>
  
  <p>Generally my question is about the data validation. What I <strong>used to</strong> 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):</p>
  
  <pre><code>// 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);
  </code></pre>
  
  <p><strong>This is wrong, right</strong> (no pun intended)<strong>? It should have been only:</strong></p>
  
  <pre><code>// 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);
  </code></pre>
  
  <p>Right?</p>