Why child entites binds to parent automatically in entity framework

c# entity-framework entity-framework-6

Question

I'm unsure of whether this is a good or negative thing, or how to adjust it.

Parent-child relationships are straightforward and evident. Nothing major. The code is displayed below:

Child Object:

public class Parent
{
    public int Id {get;set;}
    public List<Child> Childs {get;set;}
}

Young Object

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

someplace in the code (say index method of the controller)

var parent = parentRepository.FindAll(x=> x.Id == 10).ToList();
var childCollection = childRepository.FindAll(x=> x.ParentId == parent.Id).ToList();

I anticipate a when I run the code above.parent item withChilds the propertynull and childCollection which is nullParent property. But this is not taking place. After second line of code executed,parent.Childs every space is filled by the child's objects.Parent a child object's property is equal toparent which I don't want (do I need to want it?).

Why does entityframework act in that manner? What situations should I be aware of? What occurs if I alter thechildCollection without being aware of this conduct?

1
1
4/7/2016 2:26:54 PM

Accepted Answer

ZZZ_tmp
1
5/23/2017 12:15:51 PM

Popular Answer

Entity Framework is made to not only map the results of your queries to entities (objects), but also to map their relationships to properties, like many contemporary ORMs. If you make a navigational features declaration (as you have withChilds or Parent If you include properties in your classes, EF will automatically and (lazily) map those properties to the referenced entities (you can find more about navigation properties here).

By design, this behavior avoids explicitly doing join-based searches and eliminates the need to callchildRepository.FindAll(x=> ... since everything is connectedChild EF loads entities as soon as you access theChilds real estate in yourParent object.

Also keep in mind that EF includes a change tracking system, so if you make modifications to entities pulled from the database, EF will keep note of those changes and persist them the first time you callSaveChanges on the circumstances.

In addition, each DbSet functions like a repository in the EF architecture (the DbContext is a UoW and each DbSet is a repository), thus I strongly advise you to learn more about EF to prevent misusing its features or re-implementing them yourself using a different abstraction (e.g. your Repositories).



Related Questions





Related

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