使用web api由实体返回的空数据

时间:2014-03-24 20:11:47

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

我有以下实体

People
---------
People_id
report_id
last_name
first_name
----------
Navigation properties 
people1     
people2
people_location

上下文类

 public partial class myPeople : DbContext
    {
        public myPeople()
            : base("name=myPeople")
        {
            base.Configuration.ProxyCreationEnabled = false;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<people_location> project_status { get; set; }
        public DbSet<people> people { get; set; }
    }
}

EF生成的模型类


 [DataContract(IsReference = false)]
    [Serializable]
    public partial class person
    {
        public people()
        {
            this.people1 = new HashSet<person>();
            this.project_discussion = new HashSet<people_location>();
        }

        public int people_id { get; set; }
        public Nullable<int> report_id { get; set; }
        public string last_name { get; set; }
        public string first_name { get; set; }

        public virtual ICollection<people> people1 { get; set; }
        public virtual people people2 { get; set; }
        public virtual ICollection<people_location> people_location { get; set; }
    }
}

在Web API控制器

// GET api/personLoc
 public List<people> Getpeople()
    {
        return db.people.AsEnumerable().ToList();
    }

当我运行API以确保它正常工作时

../api/personLoc/

我只是得到一堆空记录

[
  {},
  {},
  {},
  {}
]

我认为问题是

的装饰
[DataContract(IsReference = false)]
    [Serializable]

当我从课程中删除它时,我得到以下异常

  

&#39; ObjectContent`1&#39;类型无法序列化内容类型的响应主体&#39; application / json; charset = utf-8&#39;。&lt; / ExceptionMessage&gt; System.InvalidOperationException&lt; / ExceptionType&gt;发生错误。&lt; / Message&gt;类型&#39; CMEApp.Entities.person&#39;的对象图包含周期,如果禁用参考跟踪,则无法序列化。&lt; / ExceptionMessage&gt;

请让我知道如何修复它。

1 个答案:

答案 0 :(得分:0)

您似乎有循环依赖。您需要在Person DataContract中将IsReference标记为true,如下所示,

 [DataContract(IsReference = true)]
    [Serializable]
    public partial class person

您可以从MSDN获取有关IsRefernce属性的更多信息。有一个类似的stackoverflow线程here