Entity Framework Code First - Reverse Engineer - entity-framework

I am about to start work on a ASP.Net MVC 4 web application using Entity Framework Code First. Because the database already exists I am using Code First's ability to perform Reverse Engineering in order to generate my domain classes.
I wish then to place these domain classes into a separate project of their own within my solution in order to keep them persistence ignorant. However, when I run the tool to reverse engineer my database (using Entity Framework Power Tools), I find that the domain classes are created, but also created is a folder called Mapping containing a mapping class for each domain class which then uses Fluent APIs to map the table properties. This is all good.
But, what I have also found, is that the mapping classes rely on a reference to the Entity Framework and I was just wondering is this thought to be poor practice? Usually when I create POCO classes, they are completely persistence ignorant, ie, there has been no reference to Entity Framework in that project at all.
Your thoughts?
Thanks.

You can keep your POCO classes in one project, while mapping stays in another project. Just add a reference to the project where POCO classes are located. Another approach is to create a data access layer and move mappings over there. That way you have three projects. Your main MVC project, your model project and data access layer that contains mappings and a reference to EntityFramework.
For example, your solution could be something like this:
1. Web User Interface (MVC)
2. Business layer
3. Unit of Work/Repository
4. Data access layer (Mapping from EF Reverse Engineering)
All four projects have access to the fifth project, Domain Model (Models from EF Reverse Engineering). Your 1 communicates with 2, 2 communicates with 3 and 3 communicates with 4. All four of these have a reference to Domain Model so you don't have to perform any type of domain model conversion between the layers.
By the way, I ignored service layer, but if you have web services or REST, you could fit it in another project, but let's not get into too many details.

Related

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

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?
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.

Confusion over MVC and entity model

My confusion stems from the fact I am using 2 different walkthroughs on building mvc applications, namely: Steven Sanderson's pro asp.net mvc and the online mvc music store. The former creates a domain model, placing the entity model in there along with repositories, while the music store demo places the entity model in the mvc model folder. Which of these is the best approach. Should the entity model and associated repositories exist in a separate domain layer, or in the MVCs model folder.
Separation of concerns
Model folder in Asp.net MVC project template is indeed very confusing. Most developers not knowing enough about MVC pattern think that application/domain model = data model. Most of the time, that's not the case.
Take for instance a user entity that may be in several different forms:
NewUser is an application model entity that has most properties of a user, plus two password properties that can be declaratively validated
User data model entity has all usual user properties and one password property
User application model entity has all the usual properties and none for password
So you can see by this simple example there are multiple models that differ between each other. And when you have a multi-assemblied application, putting application model in a separate assembly is very wise, since all assemblies will most probably communicate using these objects only. No data model entities should be transferred outside data assembly/tier to make use of SoC...
So in the end it's ok to put data model in the Model folder when building a small scale simple application, but in all other cases it's probably better to use a separate application model assembly that's shared between all assemblies. And have a separate data model that's only used in data tier assembly.
Read this answer that may help you see things a bit clearer.
And this one as well.
I would recommend against using the Model folder and use a separate assembly instead. You'll have better separation and improved scalability.
Strategically it makes sense to place the EF Model in the same folder as the repositories, because it just is a part of the Data-Access-Layer inside an application.
Logically it would be better to place the EF model in the Model directory as it creates all classes needed to reflect the database in an application. (And if you open the Class View it looks way better to have all those classes residing in a folder called Model instead of Repositories)
At our company we've had the same problem and decided to go with saving the EF model in the Model folder.
After all it's up to you what you do. The most important thing to do here would be to document all kinds decisions that happen during development (when, why and based on what).
Documenting everything could prevent later WTF's

Updating a Model in asp.net mvc

Our project manager has asked us to refactor an app that was using the Repository Pattern (it was done using Nerddinner as example) to now use a service Layer.
My problem now is that Im not sure how to Update a Model cause the UpdateModel method is supposed to be used in the controller... whats a recomended approach to updating a model using repository pattern along with a service layer??
please help
I would suggest you 'hide' your current Repository Pattern inside your service layer. Data access code should not be visible to the clients of the service.
You can implement a collection of DTOs that will be returned from service layer or accepted as parameters. Those objects can be just POCOs to hold the data in a database-agnostic way.
DTOs are usually accompanied by Adapters for translation to/from your data access classes (that represent tables). This approach allows you to change database schema without changing service layer interface.
You can treat those DTOs as models in MVC, if your project is simple and data for your views matches the service layer DTOs. You can also define your models in MVC project and let controller or another set of adapters translate models into DTOs.
My preferred design includes model that are declared in MVC (Models folder) that work with strongly-typed views. UpdateModel method then works with those classes. Next controller or ModelAdapter creates an instances of Service Layer DTOs and passes them to services. DTO adapters inside services are then responsible to populate data access classes from repository pattern.

what is the best practice approach for n-tier application development with entity framework?

I am building an application using entity framework. I am using the T4 template to generate self tracking entities.
Currently, I am thinking of creating the entity framework code in a separate project. In this same project, I would have partial classes with additional methods for the entities.
I am thinking of creating a separate project for a service layer (WCF) with methods for the upper/presentation tier. The WCF layer will reference the entity framework project. The methods in the WCF layer will return the entities or accept the entities as the parameters.
I am thinkg of creating a third project for the presentation layer (ASP.net), this will make calls to the WCF service but will also need to reference the entities as the WCF methods take these types as the parameters/return types.
In short, i want to use the STE entities generated by the T4 template as a DTO to be used in all layers.
I was originally thinking of creating a business logic layer that maps to each entities. Example: If i have a customer class, the Business Layer would have a CustomerBLL class and then methods in the customerBLL will be used by the service layer. I was also trying to create a DTO in this business layer. I however found that this approach is very time consuming and i do not see a major benefit as it would create more maintenance work.
What is the best practice for n-tier application development using entity framework 4?
You should separate your entities and their persistence logic into separate projects. That way your Presentation layer will only need to reference the project containing the entities and be persistence ignorant.
I guess the projects breakdown as the following would be a nice approach (at least it has worked out well for me :))
Entities in one project
Persistence logic in another project (Repositories, Unit of Work
implementation)
WCF in one project
Presentation layer
Hope it helps.

Where "ADO.NET Entity Framework" files in 3 layer architecture?

If I use ADO.NET Entity Framework in our project and we depend on a 3-layer architecture pattern that we have ( presentation layer - business layer - data access layer ) a project for each layer.
So when I make an entity model file where can I put it in the DAL or BL? If I put it in the DAL and from the presentation layer want to access a domain object in it through the business layer so we need to add a reference to the DAL in the presentation layer. Also, how do I get that type of an object as it is created in the DAL? On the other hand should I put the entity model file in the business layer? Which is the better and why?
Ideally, the EntityFramework generated code makes up your data layer. You would basically have some repetition then in your business layer if you needed the same sorts of objects in your business layer as you have in your data layer. Unfortunately, EntityFramework doesn't really help you at all with your business layer.
Now, you'll also read things about EntityFramework that say you can/should use it as a combined data/business layer. That violates Separation of Concerns, so I would guide you away from it, but I'm sure a ton of people do it anyway. If you wanted to move from EntityFramework to NHibernate some day, you'd be best off trying to isolate your ORM from the rest of your code base and minimize any coupling to the ORM (often through implementing something like a Repository pattern).
People who talk the language of MVC will often use EntityFramework as the Model and may or may not distinguish between a data layer and a business layer (which generally would both live in the Model). Even if you use MVC, I still believe you should decouple your data access from your business rules and business logic.
You can place the entities in a separate class library project, for example: Common Entity Library. This library can be referenced in any other app layers. You can then work with collections across application domain.
As I see it the Entity Framework is your DAL. It provides the needed tools to abstract the Model objects exposed by the Entity Framework from the persistance services of a backend database.
The Entity Framework straddles both the Business Layer and the DAL from this old three layer pattern. My advice is if you going with the Entity Framework is stop thinking in terms of Presentation->Business->Data and think more in terms of View->Model.