1
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.

  1. Is there a better way to do this? I would like to use this same style of syntax.
  2. How can I accomplish this without having to manually assign the Child to the Parent?

Thanks!

1
  • It's not code first. Commented Nov 7, 2014 at 14:41

2 Answers 2

1

The including...

FatherRepository.All().Including(x => x.Childs, x => x.Childs.Select(y => y.ChildChild)); 

Father class...

public class Father { public int Id { get; set; } #region Navigations Properties public virtual List<Child> Childs { get; set; } #endregion } 

Child class...

public class Child { public int Id { get; set; } public int ChildChildId { get; set; } public int FatherId { get; set; } #region Navigations Properties public virtual Father Father { get; set; } public virtual ChildChild ChildChild { get; set; } #endregion } 

ChildChild class...

public class ChildChild { public int Id { get; set; } } 
Sign up to request clarification or add additional context in comments.

Comments

0

Just write :

var result = this.dbContext.Parents.Where(m => m.Parent.Id == parentId) .Include(p=>p.Child).FirstOrDefault() 

result will contains corresponding childs

2 Comments

I was doing that originally but I got an error "Invalid column Child_Id"... the child's primary key doesn't exist in the parent's table. The parent's primary key exists as a foreign key in the child table.
Can you try to add [ForeignKey("ChildField")] \n public int? Child_Id { get; set; } before public Child ChildField { get; set; }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.