asp.net MVC 4 - 如何 return 减少序列化数据?

asp.net MVC 4 - How do I return less data for serialization?

我是 asp.net MVC4 的新手,我对整个数据集的序列化有疑问。

当我 return 这个数据集时,例如。 db.Prestations.ToList() 并在 Postman 中调用我的端点,请求需要很长时间并且没有响应。

如果我将 db.Prestations.ToList() 的结果放入一个变量中,然后抛出异常,我的请求中就会出现异常。

所以这似乎是一个序列化问题,比如数据 returned 太大了。

我的问题是如何删除 Prestations 中不需要的子对象?

这是我的模型,我不想 return 三个哈希集,我该怎么做?

namespace Uphair.EfModel
{
using System;
using System.Collections.Generic;

public partial class Prestation
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Prestation()
    {
        this.PartenairePrestations = new HashSet<PartenairePrestation>();
        this.PrixDureeOptions = new HashSet<PrixDureeOption>();
        this.LigneReservations = new HashSet<LigneReservation>();
    }

    public int IdPrestation { get; set; }
    public string NomPrestation { get; set; }
    public int Categorie { get; set; }
    public Nullable<int> CoifEsthe { get; set; }
    public Nullable<int> IdPrestationCategorie { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<PartenairePrestation> PartenairePrestations { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<PrixDureeOption> PrixDureeOptions { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<LigneReservation> LigneReservations { get; set; }
    public virtual PrestationCategorie PrestationCategorie { get; set; }
}
}

感谢所有愿意花时间帮助我的人:)

您可以使用 JsonIgnoreAttribute 和 DataMemberAttribute

默认情况下,Json 库将在其创建的 JSON 中包含所有 classes public 属性和字段。将 JsonIgnoreAttribute 添加到 属性 会告诉序列化程序始终跳过将其写入 JSON 结果。

[JsonIgnore]
public int Categorie { get; set; }

如果您只想序列化 class 属性的一小部分,那么解决这种情况的最佳方法是将 DataContractAttribute 添加到 class 并将 DataMemberAttributes 添加到要序列化的属性。这是选择加入序列化,与使用 JsonIgnoreAttribute.

选择退出序列化相比,只有您标记的属性被序列化
[DataContract]
public class Prestation
{  
  // included in JSON
  [DataMember]
  public int IdPrestation { get; set; }
  [DataMember]
  public string NomPrestation { get; set; }

  //ignored in JSON
  public int Categorie { get; set; }
  public Nullable<int> CoifEsthe { get; set; }
  public Nullable<int> IdPrestationCategorie { get; set; }
}