我刚刚开始学习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();
}
现在,我的数据库中有一些测试数据。当我向邮递员发出“获取请求”时,啤酒厂没有显示任何相关的啤酒。
在邮递员中,它看起来像这样:
//啤酒
{
"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
}
有什么建议吗?
查询中不包含Beer的相关实体。请包括相同的_context.Breweries.Include(brewery => brewery.Beers)
尝试一下。
return await _context.Breweries
.Include(x => x.Beers)
.ToListAsync();
https://docs.microsoft.com/en-us/ef/core/querying/related-data
您现在遇到的确切问题已在此线程中指定
.Net Core 3 and EF Core 3 Include Problem (JsonException) [Solved]