Entity Framework Core : Access parent from child

c# ef-core-2.2 entity-framework-core relationship


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.

5/30/2019 3:37:04 PM

Accepted Answer

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);
5/30/2019 12:05:15 AM

Popular Answer

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.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow