Description
I am creating the db connection like so:
protected override void OnConfiguring(DbContextOptionsBuilder optionbuilder)
{
optionbuilder.UseLazyLoadingProxies().UseSqlite(@"Data Source=Data.db");
}
And I am trying to access an object like so:
public static User GetProfile(int uid)
{
using (Db db = new Db())
{
return db.Users.Include(x => x.Settings).FirstOrDefault(x => x.UserId == uid);
}
}
The user object is as follows:
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string Name { get; set; }
public DateTime? LastUsed{ get; set; }
public virtual Setting Settings { get; set; }
}
but upon accessing Users.Settings
, it throws the error listed below.
'Error generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.LazyLoadOnDisposedContextWarning: An attempt was made to lazy-load navigation property 'Settings' on entity type 'UserProxy' after the associated DbContext was disposed.'. This exception can be suppressed or logged by passing event ID 'CoreEventId.LazyLoadOnDisposedContextWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.'
I understand what this means but it goes against my understanding of includes and how it causes eager loading.
My understanding was that when using an include and accessing the object explicitly by calling FirstOrDefault eager load the related objects to be populated immediately without the need for the db connection to remain open; but apparently, this is not the case. Am I missing something here about the usage or is this a bug?
Further information
db.Users.FirstOrDefault(x => x.UserId == uid);
works fine.
db.Users.Include(x => x.Settings).FirstOrDefault(x => x.UserId == uid);
while not invoking UseLazyLoadingProxies()
works fine.
I posted a question on SO assuming I was misusing it, but a user there directed me here informing me that it may be a bug. (https://stackoverflow.com/questions/55369146)
Steps to reproduce
Create object and connector as shown, try to include a related object and load data.
Upon accessing the include like so:
var user = User.Identity.GetProfile();
if (user.Settings != null && string.IsNullOrEmpty(user.Settings.GoogleMapsApiKey))
{
//Do things
}
The error will be thrown.
Further technical details
EF Core version: 2.2.3
Database Provider: Microsoft.EntityFrameworkCore.Sqlite
Operating system: W10
IDE: Visual Studio 2017 15.9.9