a.toraby
a.toraby

Reputation: 3391

Entity Framework 6 lazy loading issue

I have this entity:

public class Crash : BaseModel
{
    public string Message { get; set; }
    public DateTime Time { get; set; }
    public int ApplicationId { get; set; }
    public virtual Application Application { get; set; }

}

The following works perfect and navigation property Application is correct:

_context.Set<T>().ToList();

But this one those not fill the Application:

_context.Set<T>().First(expression);

The correct item is retrieved, though In the acquired item property Application is null.

What should I do to find an item with expression and still have auto loading of the navigation properties??

Upvotes: 1

Views: 92

Answers (2)

CodingYoshi
CodingYoshi

Reputation: 26989

You need to load it by including it in your query. This is known as eager loading.

_context.Set<Crash>().Include(x => x.Application).First(expression);

You can also turn off lazy loading and the navigation property will be loaded when you access it. But keep in mind this can cause performance issues. Turning lazy loading off will have a global effect.

If you just want this specific property to be loaded without having an include as I have shown above, you can make the property not virtual.

Here is a link for more information on lazy loading etc.

Upvotes: 1

Ivan Mokrov
Ivan Mokrov

Reputation: 50

First() returns only ONE single value, not a collection. Unlike ToList() do.

Your control wait for collection to come.

Single value is not a collection with only single value;

You need to create a collection with one record of your First() returned value. That will be a List of one record.

Upvotes: 0

Related Questions