Ham*_*med 0 c# nested entity-framework-core asp.net-core
我正在使用 EntityFramework (EF) Core 和 ASP.NET core。
我的模型如下:
class Zoo
{
public ICollection<Animal> Animals {set; get;}
}
class Animal
{
public ICollection<Dog> Dogs {set; get;}
}
class Dog
{
public ICollection<Shepherd> Shepherds {set; get;}
}
Run Code Online (Sandbox Code Playgroud)
(这并不完全是我的模型的定义方式,该示例足够接近,希望它可以简单地显示嵌套关系。)
我想用Zoo给定的 ,查询 a ,并在结果中id包含Animals, Dogs, 和。Shepherds我有:
var animals = await context.Zoo
.Include(zoo => zoo.Animals)
.ThenInclude(animal => animal.Dogs) // operates on the Animal type
.FirstAsync(zoo => zoo.ID = id)
Run Code Online (Sandbox Code Playgroud)
关于如何添加有什么想法Shepherds吗?
(注意:我知道Github 上的这个讨论,但不确定如何利用建议的方法来深入了解我的嵌套关系模型。)
dog.Sheperds如果您想在结果中包含,则只需继续ThenInclude调用:
var animals = await context.Zoo\n .Include(zoo => zoo.Animals)\n .ThenInclude(animal => animal.Dogs)\n .ThenInclude(dog => dog.Sheperds)\n .FirstAsync(zoo => zoo.ID = id);\nRun Code Online (Sandbox Code Playgroud)\n\n每个ThenInclude()调用都对前一个结果进行操作,因此您可以使用它来进行更深入的研究。它\xe2\x80\x99s仅Include()重置回原始级别。因此,如果您想包含多个集合,Animal例如,那么您必须从头开始:
var animals = await context.Zoo\n .Include(zoo => zoo.Animals)\n .ThenInclude(animal => animal.Dogs)\n .ThenInclude(dog => dog.Sheperds)\n .Include(zoo => zoo.Animals)\n .ThenInclude(animal => animal.Cats)\n .FirstAsync(zoo => zoo.ID = id);\nRun Code Online (Sandbox Code Playgroud)\n\n注意:使用 时ThenInclude,IntelliSense 通常会为您提供第一个在 上运行的重载的自动完成提示,TPreviousProperty而不是IEnumerable<TPreviousProperty>。如果您继续并使用正确的重载,它最终会解决这个问题,并且不会阻止您正确编译它。