【问题标题】:Empty data being returned by entity using webapi实体使用 webapi 返回的空数据
【发布时间】:2014-05-02 09:54:50
【问题描述】:

我有以下实体

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]

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

“ObjectContent`1”类型无法序列化内容类型“application/json;”的响应正文; charset=utf-8'。System.InvalidOperationException发生错误。“CMEApp.Entities.person”类型的对象图包含循环,如果禁用引用跟踪,则无法序列化。

请告诉我如何解决它。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 虽然这个答案理论上可以回答这个问题,it is better 在这里包含答案的基本部分,并提供参考链接。
    • 谢谢@hichris123。会做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2020-08-29
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2019-05-18
    相关资源
    最近更新 更多