gpt4 book ai didi

c# - EF Core 包含列表列表

转载 作者:行者123 更新时间:2023-12-05 04:00:55 25 4
gpt4 key购买 nike

我有一个非常简单的模型。主类 Recipe 包含一个 RecipeItem 列表。每个 RecipeItem 都有一个 RecipeItemComponents 列表。

使用 Entity Framework 上下文,我可以这样做:

var ret = await _context.Recipes
.Include(x => x.RecipeItems)
.ToListAsync();

此代码返回带有 RecipeItems 的食谱,但对于每个 RecipeItems,我没有 RecipeItemsComponent 列表。这是有道理的,因为我没有包括那些,但我不确定该怎么做。

谢谢

最佳答案

这是我的工作代码示例

模型

public class Parent
{
public int Id { get; set; }

public string Name { get; set; }

public virtual List<Child1> Child1s { get; set; }
}

public class Child1
{
public int Id { get; set; }

public string Name { get; set; }

public int ParentId { get; set; }
public Parent Parent { get; set; }

public virtual List<Child2> Child2s { get; set; }
}

public class Child2
{
public int Id { get; set; }

public string Name { get; set; }

public int Child1Id { get; set; }
public Child1 Child1 { get; set; }
}

在数据库上下文类中

public class TestDbContext : DbContext
{
public TestDbContext(DbContextOptions<TestDbContext> options)
: base(options)
{
Database.EnsureCreated();
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>().HasMany(x => x.Child1s).WithOne(x => x.Parent).HasForeignKey(x => x.ParentId);
modelBuilder.Entity<Child1>().HasMany(x => x.Child2s).WithOne(x => x.Child1).HasForeignKey(x => x.Child1Id);

this.InitialData(modelBuilder);
base.OnModelCreating(modelBuilder);
}

protected void InitialData(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>().HasData(new Parent[]
{
new Parent
{
Id = 1,
Name = "Parent 1",
}
});

modelBuilder.Entity<Child1>().HasData(new Child1[]
{
new Child1
{
Id = 1,
Name = "Child 1 1",
ParentId = 1,
}
});
modelBuilder.Entity<Child2>().HasData(new Child2[]
{
new Child2
{
Id = 1,
Name = "Child 2 1",
Child1Id = 1
}
});
}

public DbSet<Parent> Parent { get; set; }
public DbSet<Child1> Child1s { get; set; }
public DbSet<Child2> Child2s { get; set; }
}

Controller

public class ParentsController : Controller
{
private readonly TestDbContext _context;

public ParentsController(TestDbContext context)
{
_context = context;
} public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}

var parent = await _context.Parent
.Include(x=>x.Child1s).ThenInclude(x=>x.Child2s)
.FirstOrDefaultAsync(m => m.Id == id);
if (parent == null)
{
return NotFound();
}

return View(parent);
}
}

这是输出 enter image description here

关于c# - EF Core 包含列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55812331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com