I'm trying to use an Entity Framework object in a view page for ASP.Net MVC 3 (Razor view) and I'm pretty sure I've done this before. However, for whatever reason I can't get it to work in this project:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0012: 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'.
Source Error:
Line 1: @model Data.Post
That is referenced in the project (I can manipulate the data in the controller) but I can't get it to work in the view.
Have you tried adding:
<%@ Import namespace="System.Data.Objects.DataClasses.EntityObject" %>
This is yet another reason why you shouldn't use the EF objects directly on a page. What happens if you add a property you don't want displayed and happen to be using Html.EditorFor? That property will erroneously be written to the page for editing.
Use a ViewModel, which is nothing more than a class with the properties you want to display. Once you load your EF object up, copy the values to a ViewModel class using AutoMapper
http://automapper.codeplex.com/
See an example of what I mean here:
http://weblogs.asp.net/shijuvarghese/archive/2010/02/01/view-model-pattern-and-automapper-in-asp-net-mvc-applications.aspx
Now, if you really want to stick with the route you are currently using, then by all means use the POCO templates for Entity Framework and they will install the code generation templates (.tt) automatically in your project so your EF objects are treated as 'basic classes (i.e. POCO classes) and they will be free from this baggage you are experiencing. Your View should have no idea what data access framework you are using, and shouldn't need additional references to get it working. You are clearly blurring the layers then.
I hope that you have included
System.Data.Entity
into your project reference.
Now:
- Open your Web.config file
Go to the assemblies section:
<compilation debug="true" targetFramework="4.0">
<assemblies>
.....
</assemblies>
</compilation>
Add: <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
Hope it works!