Web Api 2和EF 6.1无法序列化

时间:2014-06-04 20:50:50

标签: c# entity-framework asp.net-web-api2 entity-framework-6.1

我遇到了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!
    }

如果我使用api/Master/1

执行get
{"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建议的那样,只需按IQueryableIList更改return db.Masters.ToList(),现在运行正常!但是,如果脚手架以这种方式生成,为什么IQueryable会失败呢?为什么IQueryable适用于EF 6.0而不是6.1?谢谢!

0 个答案:

没有答案