2012-02-08 96 views
1

我想在ASP.Net MVC 3(剃刀視圖)的視圖頁中使用實體框架對象,我很確定我以前做過這個。然而,無論出於何種原因,我不能讓它在這個項目上工作:在ASP.Net中使用實體模型對象MVC視圖頁

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 

即在項目中引用(我可以操縱控制器中的數據),但我不能讓它在工作風景。

回答

1

您是否嘗試過加入:

<%@ Import namespace="System.Data.Objects.DataClasses.EntityObject" %> 
1

這是另一個原因,你不應該在頁面上直接使用EF對象。如果添加一個您不想顯示的屬性並碰巧使用Html.EditorFor,會發生什麼情況?該屬性將被錯誤地寫入頁面進行編輯。

使用一個ViewModel,它只不過是一個具有要顯示的屬性的類。當你將你的EF對象向上的值複製到使用AutoMapper http://automapper.codeplex.com/

一個ViewModel類見我的意思在這裏一個例子:

http://weblogs.asp.net/shijuvarghese/archive/2010/02/01/view-model-pattern-and-automapper-in-asp-net-mvc-applications.aspx

現在,如果你真的想堅持您目前使用的路線,然後通過一切手段爲實體框架使用POCO模板,他們會自動將代碼生成模板(.tt)安裝到您的項目中,以便您的EF對象被視爲「基本類(即POCO類)和他們將免除您正在經歷的這種行李。你的View應該不知道你正在使用什麼數據訪問框架,並且不應該需要額外的參考才能使它工作。那麼你顯然會模糊圖層。

1

我希望你已包括

System.Data.Entity的

到您的項目參考。

現在:

  1. 打開Web.config文件
  2. 轉至組件部分: <compilation debug="true" targetFramework="4.0"> <assemblies> ..... </assemblies> </compilation>

  3. 地址:<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

希望工程!

相關問題