2017-09-16 66 views
0

我有一個Web API與本地數據庫,我使用我的數據庫模型創建了控制器。在我有外鍵的所有類模型中,我都不斷收到這個錯誤。'ObjectContent'類型無法序列化

類型 'System.Data.Entity.DynamicProxies.Product_9B61A36C2BD0C13AA03EB8B09F2678CB0976D5E84057A4447E1FAF98EBDB7865' 數據合同名稱 'Product_9B61A36C2BD0C13AA03EB8B09F2678CB0976D5E84057A4447E1FAF98EBDB7865:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' 預計不會。如果使用DataContractSerializer,則考慮使用DataContractResolver,或者將未知的任何類型靜態添加到已知類型列表中 - 例如,使用KnownTypeAttribute屬性或將它們添加到傳遞給序列化程序的已知類型列表中。

我嘗試使用[DataContract][KnownType ..][數據成員]但它一直得到這個錯誤。你知道我必須做什麼嗎?

這是我的班級代碼之一:

namespace WholesaleRetailProject 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.Runtime.Serialization; 

    [KnownType(typeof(Category))] 
    [KnownType(typeof(ProductExport))] 
    [DataContract] 
    public partial class Product 
    { 
     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] 
     public Product() 
     { 
      this.ProductExport = new HashSet<ProductExport>(); 
     } 

     public int ProductID { get; set; } 
     public int ProductCode { get; set; } 
     public string ProductName { get; set; } 
     public double ProductSellPrice { get; set; } 
     public int ProductCategoryID { get; set; } 
     public int ProductStock { get; set; } 

     [DataMember] 
     public virtual Category Category { get; set; } 
     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] 
     [DataMember] 
     public virtual ICollection<ProductExport> ProductExport { get; set; } 
    } 
+0

'ProductExport'是您定義的類嗎? –

+0

此外,還有一個有用的快捷方式,因此您不必構造一個構造函數:'public virtual ICollection ProductExport {get;組; } = new HashSet ();' –

回答

0

這是一個非常不好的做法,使用全域模型通過控制器來傳遞數據。您可以創建自定義Dto,然後使用automapper將域模型中的數據綁定到dto。在dto中,您可以刪除「部分」和「虛擬」關鍵字,並排除必要的對象屬性。

相關問題