public class Parent { public int Id { get; set; } public string Name { get; set; } public Child ChildField { get; set; } } public class Child { public int Id { get; set; } public int Age { get; set; } public int ParentId { get; set; } } public class MyDbContext : DbContext { public DbSet<Parent> Parents { get; set; } public DbSet<Child> Childs { get; set; } } DB Rows: parent_id | name 1 "Parent 1" 2 "Parent 2" Child Rows child_id | age | parent_id 3 15 1 4 21 2 I have a method that looks like this:
public Parent Get(int parentId) { var result = this.dbContext.Parents .Join( this.dbContext.Childs, p => p.Id, c => c.ParentId, (p, c) => new { Parent = p, Child = c }) .AsNoTracking().Where(m => m.Parent.Id == parentId) .FirstOrDefault() result.Parent.Child = result.Child; return result.Parent; } This is currently working for me, but I'd like to not have to manually assign the child to the parent after this join.
- Is there a better way to do this? I would like to use this same style of syntax.
- How can I accomplish this without having to manually assign the Child to the Parent?
Thanks!