[英]Entity Framework Code First One to Many relationship return data using web api
These are my model and I am using entity framework code first approach. 这些是我的模型,我正在使用实体框架代码优先方法。
public class Respondent
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RespondentId { get; set; }
public User Requester { get; set; }
public User Provider { get; set; }
public string Role { get; set; }
[NotMapped]
public ICollection<User> Providers { get; set; }
}
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public int UPI { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public bool IsPublic { get; set; }
[NotMapped]
public string Profile_Pic { get; set; }
[NotMapped]
public string Role { get; set; }
[NotMapped]
public List<string> Roles { get; set; }
}
Now I want to get all respondents by using following web api method but i am not getting correct result set and it is showing null values for Provider and requester and only returning respondent id. 现在,我想通过使用以下Web api方法来获取所有答复者,但是我没有得到正确的结果集,并且它显示Provider和Requester的空值,并且仅返回响应者ID。
public IQueryable<Respondent> GetRespondents()
{
return db.Respondents;
}
You can use the Include()
function to load related data through your model's navigation properties. 您可以使用
Include()
函数通过模型的导航属性加载相关数据。
Something like this. 这样的事情。
// GET: api/Respondents
public IQueryable<Respondent> GetRespondents()
{
return db.Respondents.
Include(user=>user.Requester)
.Include(pro=pro.Providers).ToList();
}
Note that if you are using EntityFramework Core, you need the following namespace 请注意,如果您使用的是EntityFramework Core,则需要以下名称空间
using Microsoft.EntityFrameworkCore;
Otherwise you need: 否则,您需要:
using System.Data.Entity;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.