【问题标题】:EF Core unable to return data from multiple tablesEF Core 无法从多个表返回数据
【发布时间】:2020-01-23 02:11:12
【问题描述】:

我正在使用 EF Core。我有一个这样的表结构:

public class User
{
    public User()
    {
        this.Projects = new HashSet<Project>();
    }

    [Key]
    public int Id { get; set; }
    public string name { get; set; }
    public string emailId { get; set; }

    public virtual ICollection<Project> Projects { get; set;}
}

public class Project
{   
    public Project()
    {
        this.TimeSheetData = new HashSet<TimeSheetData>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int userId { get; set; }

    [ForeignKey("userId")]
    public virtual User User {get; set; }
    public virtual ICollection<TimeSheetData> TimeSheetData { get; set;}
}

public class TimeSheetData
{
    [Key]
    public int id { get; set; }
    public int project_id { get; set; }
    [ForeignKey("project_id")]
    public virtual Project Project {get; set; }
    public string hours_logged { get; set; }
}

------------

public List<User> GetTimeSheet(int userid)
{
    var data = _context.Users.Include(u => u.Projects)
                             .ThenInclude(p => p.TimeSheetData)
                             .AsNoTracking()
                             .Where(a => a.Id == userid)
                             .ToList();
    return data;
}

返回:

[
    {
        "id": 101,
        "name": "Niranjan",
        "emailId": "godbole.niranjan@gmail.com",
        "projects": [
            {
                "id": 1,
                "name": "Niranjan",
                "userId": 101

此对象不包括时间表数据。但是当我调试从查询返回的数据时,会显示所有数据。所以我是否需要更改我的用户表以容纳时间表数据,但用户表包含项目,而项目又包含时间表。

有人可以帮我弄清楚吗?

【问题讨论】:

  • 您是否在数据库中验证了项目 Id#1 是否有 Timesheetdata?询问是因为,可能在调试中,您可能已经注意到不同项目 ID 的 Timesheetdata。您是否遇到任何您的应用程序可能忽略的异常?另外,您能否将 _context.Users.Include(u => u.Projects) .ThenInclude(p => p.TimeSheetData) .AsNoTracking() .Where(a => a.Id == userid) 抓取到一个变量中,然后查看正在执行的查询。请在数据库中执行相同的查询并在此处发布您的观察结果。

标签: c# .net asp.net-core ef-core-2.0


【解决方案1】:

您可能会在UserProjects 之间遇到循环引用。

为了防止引用循环,您可以在启动 ConfigureServices 时使用以下代码:

对于 asp.net core 2.2:

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

对于 asp.net core 3.0 (MVC/Web API),只需按照以下步骤使用 NewtonsoftJson 克服循环引用。

1.安装Microsoft.AspNetCore.Mvc.NewtonsoftJson包(版本取决于你的项目)

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.0.0

2.在startup.cs中添加以下代码

services.AddControllersWithViews().AddNewtonsoftJson(x =>
        {
            x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多