Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core : Access parent from child

Might be a silly question but I'm a bit confused here.

I have a parent entity which contains a list of children.

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

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

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

EFcore will create a ParentId as a foreign key in the table Child.

Now, let's say I want to retrieve all the children that have a specific Parent, how should I do it ? The ParentId is not available in the Child object.

Therefore, I cannot do something like:

var result = model.Child.Where(child => child.ParentId == 3);

I could add the ParentId property to the child in the entity, but I really don't want this property to be assigned manually. And if I set it as readonly by specifying the getter only, the migration doesn't work anymore.

like image 642
Robouste Avatar asked May 29 '19 19:05

Robouste


2 Answers

EF Core allows you to access the associated shadow property in LINQ to Entities query using the EF.Property method:

Addresses a given property on an entity instance. This is useful when you want to reference a shadow state property in a LINQ query. Currently this method can only be used in LINQ queries and can not be used to access the value assigned to a property in other scenarios.

All you need to know is the name and the type - in your case they are "ParentId" and int? (optional):

var result = model.Child.Where(child => EF.Property<int?>(child, "ParentId") == 3);
like image 142
Ivan Stoev Avatar answered Sep 19 '22 13:09

Ivan Stoev


I would recommend you have both the references (child-parent and parent-children) in the respective classes as provided in @ScotG answer.

However,since you dont want that, in EF using lazy loading you can do something like model.Parents.Find(3).Children since from the Parent class you have the references of its children.

like image 21
kkica Avatar answered Sep 20 '22 13:09

kkica