MVC3 and EF Data first: what are the best practices?
Asked Answered
H

1

9

It seems that most of the focus with MVC3 and EF4.1 is around "code first" - I can't seem to find any examples or tutorials that meet the following criteria:

  • uses an existing SQLServer database
  • has separate projects for web & data access (we will have multiple web apps sharing the same data access classes)
  • recommendations for validation

Does such an example or tutorial exist? Are there any documented "best practices" for how to accomplish this, or rationale for NOT having a solution structured this way?

Hardcore answered 5/7, 2011 at 15:31 Comment(0)
S
5

It is quite common scenario and it depends if you want to use EDMX file for mapping or if you want to have mapping defined in code (like code first).

Both scenarios can be done as database first

  • You will create EDMX from existing database with build in EF tools in Visual Studio and you will use DbContext T4 generator template to get POCO classes and DbContext derived class
  • You will download EF Power Tools CTP and you will use its reverse engineering feature to generate code mapping, POCO classes and context for you

Neither of these approaches will add Data annotations. Data annotations on entities should not be used for client validation (that is bad practice) unless you are doing very simple applications. Usually your views have some more advanced expectations and validation in view can be different then on entity. For example insert view and update view can need different validations and it is not possible to perform it with single set of data annotation on the entity. Because of that you should move data annotations for validation to specialized view models and transform your entities to view models and vice versa (you can use AutoMapper to simplify this).

Anyway it is possible to add data annotations to generated classes via buddy classes but as mentioned it is not a good practice.

Saar answered 5/7, 2011 at 16:7 Comment(3)
Both agree and disagree about entity data annotations. For simple constraints such and length and nullability, I think data annotations on entity classes are acceptable. Otherwise you've created an anemic domain model (martinfowler.com/bliki/AnemicDomainModel.html), an anti-pattern. Agreed, view models have more complex business scenarios and should/will have more complex validation requirements.Oneiric
Is the edmx part of the web project, or in its own class library? I've updated the question to remove annotation for validation, since I'd like to avoid the anemic domain model.Hardcore
I would use a separate class library.Oneiric

© 2022 - 2024 — McMap. All rights reserved.