2014-09-04 31 views
1

我在嘗試將EF對象存儲到視圖狀態以及大量使用Google搜索(通常以SO結尾)後遇到了一些問題,最終出現了更多問題。將EF(db優先)序列化到視圖狀態

  1. 我有一個DB頭EF 6實體模型,具有自動生成的類,其中一個被稱爲MyRole
  2. 然後我有一個DAL包裹進入EF對象..下面是摘錄重要部位

    namespace MyApp 
    { 
        public class EFDataAccess : IDisposable 
        { 
         private MyEntities context; 
    
         public static IEnumerable<MyRole> GetRoles() 
         { 
          IEnumerable<MyRole> oRet = null; 
          using (EFDataAccess oRepo = new EFDataAccess()) 
          { 
           oRet = oRepo.context.Roles.AsEnumerable(); 
          } 
          return oRet; 
         } 
        } 
    } 
    
  3. 我的ASP.Net頁面具有以下

    ViewState["lstRoles"] = EFDataAccess.GetRoles().ToList(); 
    

    現在,這裏的問題是,ASP.Net barfs說它不能添加到查看狀態爲MyRole不可序列化。

  4. 所以,按照Entity Framework: How to set model as Serializable in Entity Framework文章中,我創建一個新類

    namespace MyApp 
    { 
        [Serializable] 
        public partial class MyRole 
        { 
        } 
    } 
    
  5. 都好到現在除非我現在運行應用程序,我得到以下runtime compilation error

    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: CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<MyApp.MyRole> [c:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll]' to 'System.Collections.Generic.IEnumerable<MyApp.MyRole> [c:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll]'. An explicit conversion exists (are you missing a cast?) 
    
    
    Source Error: 
    
    Line xxxx: using (EFDataAccess oRepo = new EFDataAccess()) 
    Line xxxx: { 
    Line xxxx:  oRet = oRepo.context.CallTrackerRoles.AsEnumerable(); *** THIS LINE HIGHLIGHTED RED 
    Line xxxx: } 
    Line xxxx: return oRet; 
    
  6. 現在,這是我卡住的地方。正如它所說的那樣,它在相同類型的隱式轉換上失敗。

回答

1

您已定義了一個新類,可能位於不同的名稱空間或不同的程序集中。該課程是partial的一部分。

+0

EF db第一個生成的類標記爲「partial」,因此您可以擴展它們。兩個類都是相同的命名空間 – 2014-09-04 09:14:28

+0

但是在不同的程序集中。 「partial」純粹是一個C#概念。它不存在於元數據中。您無法擴展不同項目的類別。 – usr 2014-09-04 09:17:12

+0

我明白你在說什麼。所有的EF代碼都在Web應用程序項目中,因此會假設(不好的想法)它會被編譯。我現在要做的是將EF數據層分離成單獨的程序集和參考。我會在後面檢查 – 2014-09-04 09:20:32