当 EF 有一个实体和它自己一样有一个导航 属性 时,它不会给出完整的 json
EF does not give complete json when it has one entity that has one navigation property like itself
我在 asp.net 核心中有一个项目,在这个项目中,我有两个实体。第一个实体是产品
public class Product
{
public int id { get; set;}
public string Name { get; set; }
public virtual Brand Brand { get; set; }
}
我的第二个class是
public class Brand
{
public Brand()
{
Products = new List<Products>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Product> Products { get; set; }
}
我有一个像这样的 APIController
public class APIController : ControllerBase
{
public object GetProducts()
{
return decorDB.Products
.Include(p => p.Brand);
}
}
我得到的是这样的json
[
{
"id":1,
"name":"iPhone",
"brand":
{
"id":1,
"name":"Apple",
"products":[
如您所见,它并不完整,我认为 EF 会中断它以防止循环。
我想要这样的东西
[
{
"id":1,
"name":"iPhone",
"brand":
{
"id":1,
"name":"Apple",
"products":[]
}
}
]
我不知道该做什么!
免责声明:未经测试但渴望发表评论。
我建议进行以下更改:
首先尝试更改您的操作结果签名:
public IEnumerable<Product> GetProducts()
下一步:尝试在启动时明确禁用往返:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
我在 asp.net 核心中有一个项目,在这个项目中,我有两个实体。第一个实体是产品
public class Product
{
public int id { get; set;}
public string Name { get; set; }
public virtual Brand Brand { get; set; }
}
我的第二个class是
public class Brand
{
public Brand()
{
Products = new List<Products>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Product> Products { get; set; }
}
我有一个像这样的 APIController
public class APIController : ControllerBase
{
public object GetProducts()
{
return decorDB.Products
.Include(p => p.Brand);
}
}
我得到的是这样的json
[
{
"id":1,
"name":"iPhone",
"brand":
{
"id":1,
"name":"Apple",
"products":[
如您所见,它并不完整,我认为 EF 会中断它以防止循环。 我想要这样的东西
[
{
"id":1,
"name":"iPhone",
"brand":
{
"id":1,
"name":"Apple",
"products":[]
}
}
]
我不知道该做什么!
免责声明:未经测试但渴望发表评论。
我建议进行以下更改:
首先尝试更改您的操作结果签名:
public IEnumerable<Product> GetProducts()
下一步:尝试在启动时明确禁用往返:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});