I've been searching a bit on this but thus far haven't been able to find a decent solution. I'm trying to get an entity from my database without the related entities attached to it.
The function goes as following
return context.Entity.SingleOrDefault(n => n.Name == name) where
context is a DbContext.
As of now the reply contains only one Entity but with an added 50 "child" entities which I do not need.
What would be the best way to go about getting a single entity from the db?
EFC2.1 pre release build
Also found that if you use
DbContext.Entity.AsNoTracking you can get the entity without the child collections.
Not sure if the full entity will be saved after making changes and calling
You have to enable Lazy Loading, simply add a property to your class like this.
public virtual ICollection<ChildType> NavigationProperty;
Here is a very useful document for Loading Related Data.
I recently discovered that you can also use
DbContext.Entity.AsNoTracking() for this purpose.
Using a linq query when fetching an entity will cause all related entities contained in the linq to also be fetched.
Say you have
a Teacher, a Student and a Classroom entity. A Teacher can have multiple Students and Classrooms. You want to find all Teachers with classroom A and all male students so you would do
DbContext.Teachers.Where(x => x.Classroom.Name = "A" && x.Student.Gender = "Male")
This will fetch the
Teacher entities with all underlying
Students since you called on them in the linq expression.
Since you want just the Teacher entity you should use the following :
DbContext.Teachers.AsNoTracking().Where(x => x.Classroom.Name = "A" && x.Student.Gender = "Male")
AsNoTracking() you declare that you do not want the underlying data and just need it to filter through the entity you do want.