我创建了一个Web,用于使用实体框架6(数据库优先)连接和更新Server中的数据。
我注意到当我为我的表生成控制器时,Get<XXX>函数只返回表行,而不包括子行。
我可以用System.Data.Entity.Include扩展方法修复这个问题吗?
然而,当我做了一个简单的测试来检索表行及其关联的子行时,我会得到响应。
StatusCode: 500,ReasonPhrase:“内部服务器错误”,
我的代码如下:
// GET: api/Fields/5
[ResponseType(typeof(Field))]
public async Task<IHttpActionResult> GetField(Guid id)
{
Field field = await db.Fields.Include(x=>x.Layers).FirstOrDefaultAsync(i => i.FieldKey == id);
if (field == null)
{
return NotFound();
}
return Ok(field);
}如果我使用原始生成的代码,没有包含,它可以很好地工作。
我在DbContext构造函数中禁用了延迟加载和代理:
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;发布于 2020-02-14 03:08:25
我发现原因是因为默认的JSON序列化程序不能正确序列化实体之间的任何循环引用
答案是
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);在……里面
公共静态类WebApiConfig {公共静态空寄存器(HttpConfiguration配置)
https://stackoverflow.com/questions/60185457
复制相似问题