使用webapi的实体返回空数据
本文关键字:数据 返回 实体 webapi 使用 | 更新日期: 2023-09-27 17:52:59
我有以下实体
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'包含循环,如果引用跟踪被禁用,则无法序列化。
你似乎有一个循环依赖。您需要在Person DataContract中将IsReference标记为true,如下所示:
[DataContract(IsReference = true)]
[Serializable]
public partial class person
您可以从MSDN中获得有关isreference属性的更多信息。这里有一个类似的stackoverflow线程