C# asp.net MVC 4-如何为序列化返回较少的数据?

C# asp.net MVC 4-如何为序列化返回较少的数据?,c#,asp.net-mvc-4,entity-framework-6,C#,Asp.net Mvc 4,Entity Framework 6,我是asp.net MVC4新手,对整个数据集的序列化有问题 当我返回这个数据集(例如db.Prestations.ToList)并在Postman中调用我的端点时,请求花费了很多时间并且没有响应 如果我将db.Prestations.ToList的结果放入一个变量,然后抛出一个异常,那么我会在请求中得到该异常 所以这似乎是一个序列化问题,比如返回的数据太大 我的问题是如何删除预设中不需要的子对象 这是我的模型,我不想让它返回三个哈希集,我该怎么做 namespace Uphair.EfMode

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

当我返回这个数据集(例如db.Prestations.ToList)并在Postman中调用我的端点时,请求花费了很多时间并且没有响应

如果我将db.Prestations.ToList的结果放入一个变量,然后抛出一个异常,那么我会在请求中得到该异常

所以这似乎是一个序列化问题,比如返回的数据太大

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

这是我的模型,我不想让它返回三个哈希集,我该怎么做

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中包含所有类公共属性和字段。将JsonIgnoreAttribute添加到属性会告诉序列化程序始终跳过将其写入JSON结果

[JsonIgnore]
public int Categorie { get; set; }
如果您只想序列化类属性的一小部分,那么解决此情况的最佳方法是将DataContractAttribute添加到类中,并将DataMemberAttribute添加到要序列化的属性中。这是opt-in序列化,与使用JsonIgnoreAttribute的opt-out序列化相比,只能序列化您标记的属性

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

问题是您正在将EF实体返回到外部世界,这应该避免。使用DTO/ViewModel并仅放置所需的数据您是否尝试使用[NonSerialized]属性?还要注意虚拟导航属性,它们可能会序列化整个数据库。请参阅我给a的答案。看起来是相同的原因,相同的解决方案或非常相似。@Camilloteriento我该怎么做呢?我的问题终于在别处了,但我仍然认为你的答案是可以接受的,因为你的信息是相关的。