Json 如何在asp.net mvc web api中忽略导航属性

Json 如何在asp.net mvc web api中忽略导航属性,json,entity-framework,asp.net-web-api,asp.net-web-api2,Json,Entity Framework,Asp.net Web Api,Asp.net Web Api2,我将ASP.NET Web API与实体框架一起使用,但在为导航属性生成JSON时遇到了一个问题: 我有两张桌子;产品和类别 public class Product { public int ProductID { get; set; } public string ProductName { get; set; } public virtual Category Category { get;

我将ASP.NET Web API与实体框架一起使用,但在为导航属性生成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; }
    }
公共类产品
{
public int ProductID{get;set;}
公共字符串ProductName{get;set;}
公共虚拟类别{get;set;}
}
公共类类别
{    
public int CategoryID{get;set;}
公共字符串CategoryName{get;set;}
公共虚拟ICollection产品{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; }
}
公共类类别
{    
public int CategoryID{get;set;}
公共字符串CategoryName{get;set;}
[JsonIgnore]
公共虚拟ICollection产品{get;set;}
}

使用此设置,每当类别序列化为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; }
}
公共类类别
{    
public int CategoryID{get;set;}
公共字符串CategoryName{get;set;}
[JsonIgnore]
公共虚拟ICollection产品{get;set;}
}

使用此设置,每当类别序列化为Json时,它都会忽略产品集合

JsonIgnore属性在EDMX更改或更新时消失。。如何保存它?在EDMX更改或更新时,JsonIgnore属性消失。。你如何保存它?