2011-08-25 38 views
0

我在.NET Entity Framework 4.0中工作 我正在使用viewstate來保存一個實體。我也序列化了這個實體。但是,當我嘗試將數據保存到視圖狀態,收到此錯誤:在實體框架中保存ViewState時出錯

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Error serializing value 'System.Collections.Generic.List`1[Pc.PrecisionCare2.ModelTypes.Medication]' of type 'System.Collections.Generic.List`1[[Pc.PrecisionCare2.ModelTypes.Medication, PrecisionCare2ModelTypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].' 
+1

是否有可能看到更多的代碼? – Bobby

+0

我還要問,爲什麼你使用的視圖狀態,而不是會議?這取決於你的需求量的但我問的原因是因爲我確定你已經知道這個,但ViewState的生命範圍是當前頁面,這意味着當你移動到另一個頁面時,ViewState將被自動銷燬。然而,Session對象存儲在內存在Web服務器上,因此可用於任何頁面,直到會話過期或應用程序會話終止,或在您的代碼中手動銷燬 – Bobby

+0

我正在將此與當前頁面一起使用。問題是,我的實體也包含另一個實體。而且我沒有序列化包含的實體。這就是發生這種錯誤的原因。我序列化包含的實體,現在一切正常。 – asma

回答

1

也許這將幫助任何人。我想自己在Viewstate中序列化一個實體,並找不到一個好的解決方案(XMLSerialization,Byte Serializing,DataContract)。我發現的是,我可以「擴展」代碼生成的類(它們是部分的)並使其可序列化。

例如,這是一個.NET代碼生成的實體:

//------------------------------------------------------------------------------ 
// <auto-generated> 
//  This code was generated from a template. 
// 
//  Manual changes to this file may cause unexpected behavior in your application. 
//  Manual changes to this file will be overwritten if the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

namespace OAuthServerBroker.EF 
{ 
    using System; 
    using System.Collections.Generic; 

    public partial class ResourceOwner 
    { 
     public ResourceOwner() 
     { 
      this.Grant = new HashSet<Grant>(); 
     } 

     public System.Guid ResourceOwner_ID { get; set; } 
     public string ResourceOwner_Username { get; set; } 

     public virtual ICollection<Grant> Grant { get; set; } 
    } 
} 

當我創建具有相同類名和命名空間,我可以讓實體序列化:)一個新的類文件。

using System; 

namespace OAuthServerBroker.EF 
{ 
    [Serializable] 
    public partial class ResourceOwner 
    { 
     public EntityState State { get; set; } //can even put into new properties 
    } 
} 

希望這可以幫助任何人,因爲它是一個古老的職位:(。