我对 WebApi2 和 EF 6.1 有问题(代码优先)
我有 2 个模型(主-详细信息)
namespace testApp.Model
{
public class Master
{
public Master () {
Details = new HashSet<Detail>();
}
[Key]
public long ID { get; set; }
[Index("IX_ComplexIndex", 0, IsUnique=true)]
public long UserID { get; set; }
[Index("IX_ComplexIndex", 1, IsUnique = true)]
public Nullable<long> TenantID { get; set; }
[ForeignKey("MasterID")]
public virtual ICollection<Detail> Details { get; set; }
}
public class Detail
{
[Key]
public long ID { get; set; }
[Index("IX_Master")]
public long MasterID { get; set; }
[MaxLength(255)]
public string Desc { get; set; }
[ForeignKey("MasterID")]
public virtual Master Master { get; set; }
}
}
ApiController
public class MasterController : ApiController
{
private TestContext db = new TestContext();
// GET api/Master
public IQueryable<Master> GetMasters()
{
return db.Masters;
} //THIS FAILS
//GET api/Master/5
[ResponseType(typeof(Master))]
public IHttpActionResult GetMaster(long id)
{
Master master = db.Masters.Find(id);
if (master == null)
{
return NotFound();
}
return Ok(master);
} //THIS WORKS FINE!
}
如果我执行 get withapi/Master/1
{"Detailss":[{"ID":1,"MasterID":1,"Desc":"test"}],"ID":1,"UserID":1,"TenantID":1}
但是如果我执行api/Master
我得到的错误消息是:
{"Message":"An error has occurred.",
"ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json;
charset=utf-8'.",
"ExceptionType":"System.InvalidOperationException","StackTrace":null,
"InnerException":{
"Message":"An error has occurred.",
"ExceptionMessage":"Error getting value from 'Details' on
'System.Data.Entity.DynamicProxies.Master_6110B4795BCBF52E3140C9F99EB1E28BF43BA97EB02A532B9C89FD1996CE11E9'.",
"ExceptionType":"Newtonsoft.Json.JsonSerializationException",
"StackTrace":"
at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues
(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter ...
我在 WebApiConfig.cs 中强制以 JSON 格式响应
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// Remove default XML handler
var matches = config.Formatters
.Where(f => f.SupportedMediaTypes
.Where(m => m.MediaType.ToString() == "application/xml" ||
m.MediaType.ToString() == "text/xml")
.Count() > 0)
.ToList();
foreach (var match in matches)
config.Formatters.Remove(match);
重要提示:如果我使用 EF 6.0(删除不支持的索引属性和其他属性),这可以正常工作。所以我很困惑!
提前致谢。
Ps:我对 C#(以及 WebApi 和 EF)真的很陌生
编辑:正如Wiktor Zychla建议的那样,只需更改一下IQueryable
,IList
现在就return db.Masters.ToList()
可以正常工作了!但是,如果脚手架以这种方式生成,为什么 IQueryable 会失败?以及为什么 IQueryable 适用于 EF 6.0 而不是 6.1?谢谢!