0

I do apologise if this has been asked before. I'm trying to research but I also don't know what I'm supposed to search, sorry. So I'm trying to get the Parent and Child to link together on my project. What I have is this:

public class ParentDb
{
  public int Id { get; set; }
  public string Title { get; set; }
  public string Description { get; set; }
}

public class ChildDb
{
  public int Id { get; set }
  public string FirstName { get; set; }
public string LastName { get; set; }
}

I assume I'm supposed to do something like:

public List<ChildDb> Children { get; set; }

I'm clueless on how I can make it so when I add to my ChildDb using the controller, it'll also add to the list of the parent when I get all parents(and child).

Sorry again if it's been asked before or I'm an idiot. I'm trying, I just don't know what I'm looking for.

1
  • Your question isn't clear. Please edit and clarify: "when I add to my ChildDb using the controller" -- what exactly do you mean by this? If you show us the code demonstrating what you mean, it will help us understand. Also, what exactly do you mean by "it'll also add to the list of the parent when I get all parents(and child)" ? Again, show us the code that demonstrates "get all parents(and child)" and explain what problem you have with that code. Commented Oct 29, 2024 at 22:49

1 Answer 1

0

To set up a parent-child relationship in Entity Framework, try the following:

  1. Define Models: Add a collection in ParentDb and a foreign key in ChildDb.

    public class ParentDb
    {
        public int Id { get; set; }
        public List<ChildDb> Children { get; set; } = new List<ChildDb>();
    }
    
    public class ChildDb
    {
        public int Id { get; set; }
        public int ParentId { get; set; }
        public ParentDb Parent { get; set; }
    }
    
  2. Configure DbContext (optional, EF can infer this):

    modelBuilder.Entity<ParentDb>()
        .HasMany(p => p.Children)
        .WithOne(c => c.Parent)
        .HasForeignKey(c => c.ParentId);
    
  3. Add a Child: Set the ParentId and add to the parent's Children.

    parent.Children.Add(child);
    _context.SaveChanges();
    
  4. Retrieve Parent with Children:

    var parent = _context.Parents.Include(p => p.Children).FirstOrDefault(p => p.Id == parentId);
    

This should link ParentDb and ChildDb effectively.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.