views:

90

answers:

1

Ok I've just ran into this and I was only supposed to be checking my emails however I've ended up watching this (and not far off subscribing to TekPub).

http://tekpub.com/production/starter

Now this app is a great starting point, but it raises one issue for me and the development process I've been shown to follow (rightly or wrongly). There is no conversion from the LinqToSql object when passing data to the view. Are there any negitives to this?

The main one I can see is with validation, does this cause issues when using MVC's built in validation as this is somthing we use extensivly. Because we are using the built in objects generated by LinqToSql how would one go about adding validation, like

[Required(ErrorMessage="Name is Required")]
public string Name {get;set;}

Interested to understand the benifits of this methodology and any negitives that, should we take it on, experiance through the development process.

Should this be taken as a guide and we should be using ViewModels? If so should we always use them even in simple cases? And how/where in the application logic does the Entity get converted to a ViewModel?

+1  A: 

With entity objects, you could use buddy classes, whereby you create a second class which acts as a metadata provider for your entity. For instance, with a Customer entity generated by Linq-to-Sql, I could create a buddy class like so:

[MetadataType(typeof(CustomerMeta))]
partial class Customer {

}

public class CustomerMeta {

  [DisplayName("Forename", Required(ErrorMessage = "Forename is required.")]
  public string Forename { get; set;}
}

Entities are generated as partial classes so you can add your own code to them.

Alternatively, you could forego pushing your entity types to your views and create specific models based around the functionality required, for instance I would typically have a User entity, but when I need to create a User, I have something called a CreateUserSpec model:

public class CreateUserSpec
{
  [DisplayName("Forename")]
  public string Forename { get; set; }
}

Which has a subset of the properties of the User, only those required to create a User. This is the model I would pass to my view, and repopulate from the form data. For instance:

public class AccountController
{
  public ActionResult Register() {
    return View(new CreateUserSpec());
  }

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult Register(CreateUserSpec spec) {
    if (!ModelState.IsValid) {
      return View(spec);
    }

    var user = UserFactory.CreateUser(spec);

    // Redirect to authorisation page?
  }
}
Matthew Abbott
@Matthew Abbott, Thanks - Where in your application logic do you perform the transfer from Entity to Model?
Pino
Depends how you manage your concerns. I'm favouring thin controllers at the moment, so the majority of work is being done through factories or repositories. I've updated the example above.
Matthew Abbott