【问题标题】:Can't get related data in ASP.Net from models无法从模型中获取 ASP.Net 中的相关数据
【发布时间】:2020-02-13 08:03:09
【问题描述】:

我刚开始学习 ASP.Net Core,但在关系方面有些问题。

在我的 Beer 模型中,我有以下导航属性:

/* Navigation Properties */
public int BreweryID { get; set; }
public Brewery Brewery { get; set; }

在我的 Brewery 模型中,我有以下导航属性:

/* Navigation Properties */
public ICollection<Beer> Beers { get; set; }

我的 dbContext 如下所示:

modelBuiler.Entity<Beer>()
            .HasOne(c => c.Brewery)
            .WithMany(u => u.Beers)
            .HasForeignKey(c => c.BreweryID)
            .IsRequired()
            .OnDelete(DeleteBehavior.Restrict);

在控制器中,我这样询问我的数据:

// GET: api/brewery
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Brewery>>> GetBreweries()
    {
        return await _context.Breweries.ToListAsync();
    }

现在,我的数据库中有一些测试数据。 当我向 Postman 发出 Get 请求时,啤酒厂没有显示任何相关的啤酒。

在 Postman 中,它看起来像这样:

//啤酒

{
    "id": 11,
    "name": "test",
    "brand": "test",
    "alcoholContent": 2,
    "platoScale": 4,
    "description": "test",
    "breweryID": 7,
    "brewery": null,
    "imageID": 3,
    "image": null,
    "foodpairings": null,
    "categoryID": 1,
    "category": null,
    "favorites": null
},
{
    "id": 12,
    "name": "test",
    "brand": "test",
    "alcoholContent": 4,
    "platoScale": 7,
    "description": "test",
    "breweryID": 7,
    "brewery": null,
    "imageID": 4,
    "image": null,
    "foodpairings": null,
    "categoryID": 1,
    "category": null,
    "favorites": null
},

//啤酒厂

 {
    "id": 7,
    "name": "Moortgat",
    "address": "test",
    "founder": "test",
    "foundationYear": "2008-01-10T00:00:00.123",
    "description": "test",
    "website": "test",
    "beers": null,
    "imageID": 3,
    "image": null
}

有什么建议吗?

【问题讨论】:

    标签: c# asp.net entity-framework linq-to-entities


    【解决方案1】:

    您现在遇到的确切问题已在此线程中指定

    .Net Core 3 and EF Core 3 Include Problem (JsonException) [Solved]

    【讨论】:

      【解决方案2】:

      试试这个。

      return await _context.Breweries
          .Include(x => x.Beers)
          .ToListAsync();
      

      https://docs.microsoft.com/en-us/ef/core/querying/related-data

      【讨论】:

      • 感谢您的回答。我之前尝试过这个,但我在 Postman 中收到错误响应。错误是:System.Text.Json.JsonException:检测到不支持的可能对象循环。这可能是由于循环或对象深度大于最大允许深度 32 造成的。
      • 假设您使用的是 Core 3.0,也许这些文章会有所帮助:link1link2
      【解决方案3】:

      查询中不包含 Beer 的相关实体。请包括相同的 _context.Breweries.Include(brewery=>brewery.Beers)

      【讨论】:

      • 感谢@Dee P 的回答。当我这样做时,我得到一个异常响应。 System.Text.Json.JsonException:检测到不支持的可能对象循环。这可能是由于循环或对象深度大于最大允许深度 32 造成的。
      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 2018-06-09
      • 2021-10-07
      相关资源
      最近更新 更多