jdavis
jdavis

Reputation: 8665

Best Practices for separation of project layers using ASP.NET MVC3 and Entity Framework

I have a solution containing an MVC3 web application and a data project with contains the Entity Framework file. I've got Entity Framework working, but when I try to include an Entity Framework Entity Item object into one of my view models to pass to a view, I'm getting the following error

The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

I've tried to add the reference to that assembly and then include it with a using statement in the project, but it doesn't seem to be doing anything. But having this problem is also begging the question: Is it not a good idea to try to use Entity Framework entity items in your view models at all? According to best practices when using ASP.NET MVC3 and Entity Framework, what are the best rules of thumb that govern where what should happen in your presentation layer, your business layer, and your data layer, and how are these separated?

I know this is involved question...

Thanks for the help.

Upvotes: 0

Views: 1222

Answers (2)

Pure.Krome
Pure.Krome

Reputation: 87047

Ok. This is my opinion of things...

First of all, your ViewModels should NEVER contain complex types in them. Complex, being Entity Framework stuff, etc. They should always been simple and clean and light. The view doesn't need to have any knowledge about persistence or database or whatnot. All a view needs to know is what data it should render. Simple.

So ViewModels should be POCO's -> strings, ints, basic custom objects and strongly typed collections.

In your controller, you should convert any complex types to view models. I recommend using AutoMapper for this.

Here is a sample tutorial website I've done which shows you how the Controller passes across the information to the ViewModel .. and the ViewModel is really simple.

Upvotes: 6

rouen
rouen

Reputation: 5134

You are getting this error because your domain objects inherit from EntityObject, so they are not persistence-ignorant. You need to use POCO generation template, or EF Code first, if you want them not to be dependent from Entity framework library.

And personally i think it is just fine to work with your domain objects in your "presentation" layer, if you are not building something huge and super-maintanable, separating domain model entirely by Automapper or so, is just total overengeering.

Upvotes: 0

Related Questions