Haraldur
Haraldur

Reputation: 237

Entity Framework Core get entity without related entities

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?

Using EFC2.1 pre release build

Edit:

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 DbContext.saveChanges()

Upvotes: 2

Views: 3791

Answers (2)

Haraldur
Haraldur

Reputation: 237

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 Classrooms and 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")

Using AsNoTracking() you declare that you do not want the underlying data and just need it to filter through the entity you do want.

Upvotes: 3

Vivek Nuna
Vivek Nuna

Reputation: 1

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.

Upvotes: 3

Related Questions