【问题标题】:The 'ObjectContent' type failed to serialize“ObjectContent”类型无法序列化
【发布时间】:2017-09-16 22:15:03
【问题描述】:

我有一个带有本地数据库的 Web API,我在其中使用我的数据库模型创建了控制器。在我有外键的所有类模型中,我不断收到此错误。

类型 'System.Data.Entity.DynamicProxies.Product_9B61A36C2BD0C13AA03EB8B09F2678CB0976D5E84057A4447E1FAF98EBDB7865' 与数据合同名:预计不会 'Product_9B61A36C2BD0C13AA03EB8B09F2678CB0976D5E84057A4447E1FAF98EBDB7865 http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'。如果您使用 DataContractSerializer 或将任何静态未知的类型添加到已知类型列表中,请考虑使用 DataContractResolver - 例如,通过使用 KnownTypeAttribute 属性或将它们添加到传递给序列化程序的已知类型列表中。

我尝试使用 [DataContract][KnownType..][DataMember] 但它不断收到此错误。你知道我要做什么吗?

这是我的课程代码之一:

    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; }
    }

【问题讨论】:

  • ProductExport 是你定义的类吗?
  • 另外,还有一个有用的快捷方式,因此您不必创建构造函数:public virtual ICollection&lt;ProductExport&gt; ProductExport { get; set; } = new HashSet&lt;ProductExport&gt;();

标签: c# entity-framework asp.net-web-api


【解决方案1】:

使用完整域模型通过控制器传递数据是一种非常糟糕的做法。您可以创建自定义 Dto,然后使用 automapper,将数据从域模型绑定到 dto。在 dto 中,您可以删除“部分”和“虚拟”关键字,并排除必要的对象属性。

【讨论】:

    猜你喜欢
    • 2016-09-15
    • 2017-07-17
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2013-08-10
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多