簡體   English   中英

如何忽略ASP.NET MVC Web API中的導航屬性

[英]How to ignore navigation properties in asp.net mvc web api

我將ASP.NET Web API與Entity Framework結合使用,但是在為導航屬性生成JSON時遇到問題:

我有兩個桌子。 產品和類別。

    public class Product
        {
            public int ProductID { get; set; }
            public string ProductName { get; set; }

            public virtual Category Category { get; set; }
        }

public class Category
    {    
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }

當我生成產品的JSON時,它會生成很好的JSON類別,但是在類別JSON內有另一個指向JSON產品的JSON,因此創建了一個巨大的JSON文件,我嘗試通過刪除虛擬的來解決此問題,但是每次更新模型我面臨同樣的問題。 有什么辦法解決嗎?

如果使用的是Newtonsoft.Json,則只需將屬性[JsonIgnore]應用於要忽略的屬性。

public class Category
{    
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }

    [JsonIgnore]
    public virtual ICollection<Product> Products { get; set; }
}

使用此設置,每當將類別序列化為Json時,它將忽略Products集合

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM