我使用MVC 6 rc1与EF 7 rc 1 Code First Model通过web api控制器检索数据.我有3个类似于下面的表.
class Product { public int Id { get; set; } public string SomeProperty { get; set; } public virtual ICollectionCategorizations { get; set; } public DateTime SomeProperty2 { get; set; } public string SomeProperty3 { get; set; } public string SomeProperty4 { get; set; } } // NOTE: Entity key should be (ProductId, CategoryId) class Categorization { public int ProductId { get; set; } public Product Product { get; set; } public int CategoryId { get; set; } public Category Category { get; set; } } class Category { public int Id { get; set; } public ICollection Categorizations { get; set; } }
我的控制器:
[ActionName("searchProducts")] public IEnumerablesearchProducts(string searchText,int? id) { var ret= db.Products .Include(s => s.Categorizations).Take(2).ToList(); return ret; }
下面是我的Startup.cs ConfigureServices部分.
services.AddMvc() .AddJsonOptions(options=> { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; }); services.AddCors(); var connectionString = Configuration.GetSection("Data:DefaultConnection:ConnectionString").Value; services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(connectionString)); services.AddSingleton(_ => Configuration); services.AddSingleton ();
当我调用api时,我得到的错误是"在Fiddler中,Chunked body没有正确地终止0大小的块".在fiddler结果集中,我只看到具有属性的预期结果集的第一个对象,直到填充了分类并且在此之后没有属性和剩余对象(不完整的JSON数据).如果我在结果集中不包含分类,则它可以正常工作.我错过了什么吗?注意:EF正确地返回数据,但它在api调用中被分块,客户端无法完整地读取数据.
发现了这个问题.检测到属性"Product"的自引用循环,类型为"Product".路径'[0] .Categorizations [0]'.
因此,EF会填写Product对象中的Categorization集合以及Categorization中的Product对象.因此,在序列化为json时,它变成了一个无限循环,如:
产品>分类(eachCategorization - 产品>分类(eachCategorization - 产品>分类(eachCategorization - 产品>分类(....
解决方案:更改Startup.cs ConfigureServices部分,如下所示
services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; });