Skip to content

Instantly share code, notes, and snippets.

@souri-t
Created March 15, 2023 14:57
Show Gist options
  • Save souri-t/bb9df24edb60d12c675a11601b0005f4 to your computer and use it in GitHub Desktop.
Save souri-t/bb9df24edb60d12c675a11601b0005f4 to your computer and use it in GitHub Desktop.

Entity Framework Coreで以下のように1対多の関係を持つクラスがあります。 Parent.ParentIdが外部キーです。 コントローラーのGetメソッドでParentの配列を取得する際にChild.nameを含んで取得する方法を教えて下さい。

public class Parent { public string name; public List childs; }

public class Child { public int id; public int ParentId; public string name; public Parent parent; }

using Microsoft.EntityFrameworkCore;

public class ParentController : Controller { private readonly YourDbContext _context;

public ParentController(YourDbContext context) {
	_context = context;
}

public async Task<IActionResult> GetParents() {
	var parents = await _context.Parents
		.Include(p => p.Childs)
		.Select(p => new {
			p.Name,
			ChildNames = p.Childs.Select(c => c.Name).ToList()
		})
		.ToListAsync();

	return Ok(parents);
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment