Lazy loading from unmapped property with entity constructor injection
Loading navigation from unmapped entity property returns errors.
Steps to reproduce
Query:
var authors = _context.Posts.Select(x => new
{
Authors = x.Authors
});
Entity class:
public class Post
{
private ILazyLoader LazyLoader { get; set; }
private Post(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
public Post()
{
}
[NotMapped] public IEnumerable<string> Authors
{
get
{
return _messages == null ? null : _messages.Select(x => x.Authors);
};
}
private ICollection<Message> _messages; //Backing field for Messages
public ICollection<Message> Messages { get; set; } //Navigation property
}
Result is expected: navigation not loaded, cause it is not included in projection and with DBSet Include() extension.
When trying to use lazy loading inside unmapped property with navigationName param on Load() extension with this code:
[NotMapped] public IEnumerable<string> Authors
{
get
{
LazyLoader.Load(this, "Messages");
return Messages.Select(x => x.Authors);
};
}
we've got this error:
'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning: An attempt was made to lazy-load navigation property 'Messages' on detached entity of type 'Post'. Lazy-loading is not supported for detached entities or entities that are loaded with 'AsNoTracking()'.'. This exception can be suppressed or logged by passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
And with this code (lazy loading with navigationField param):
[NotMapped] public IEnumerable<string> Authors
{
get
{
LazyLoader.Load(this, ref _messages);
return _messages.Select(x => x.Authors);
};
}
we've got this error:
The property 'Authors' on entity type 'Post' could not be found. Ensure that the property exists and has been included in the model.
Further technical details
EF Core version: 2.1 Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: MS Windows 10 IDE: Visual Studio 2017 15.7.5
@vsopko The query does not result in any entities being tracked because it projects an anonymous object out of the results. Also, this means that the query does not return Posts objects, so it's unclear to me how the Authors in the Post class is being called. Regardless, the first exception message indicates that lazy-loading on untracked entities is not supported--see #10042. The second exception indicates that Authors is not mapped as a navigation property, which is because of the [NotMapped] attribute.
In a nutshell, lazy-loading needs a mapped navigation property, a context that hasn't been disposed, and, until #10042 is implemented, a tracked entity.
@ajcvickers Thank you for explanation, and sorry for bothering: is there any workaround to load navigation properties with DI inside entity model? May be context injection doesn't require mapped property? I want to make navigations private and produce query output with not mapped properties, calculated on navigations loaded inside entity and some business logic. Something like this:
public class Entity
{
...
private ICollection<ChildEntity> children { get; set; }
[NotMapped]
public ICollection<DTO> collection
{
get
{
return
{
// load children navigation
// return ICollection<DTO>, based on linq queriyng children
};
}
}
}
@vsopko Everything mapped can be made private if you want. For example:
public class Blog
{
private int Id { get; set; }
private ICollection<Post> Posts { get; set; }
}
public class Post
{
private int Id { get; set; }
private Blog Blog { get; set; }
}
public class BloggingContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Blog>(b =>
{
b.Property("Id");
b.HasMany<Post>("Posts").WithOne("Blog");
});
builder.Entity<Post>(b =>
{
b.Property("Id");
});
}
}
However, if you want lazy-loading with proxies, then EF needs to be able to inherit from the entity type and override the navigation properties. This means they must be at least protected:
public class Blog
{
private int Id { get; set; }
protected virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
private int Id { get; set; }
protected virtual Blog Blog { get; set; }
}
public class BloggingContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Blog>(b =>
{
b.Property("Id");
b.HasMany<Post>("Posts").WithOne("Blog");
});
builder.Entity<Post>(b =>
{
b.Property("Id");
});
}
}
Or you could use a non-proxy lazy-loading pattern. For example:
public class Blog
{
private ICollection<Post> _posts;
private Blog(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
private ILazyLoader LazyLoader { get; set; }
private int Id { get; set; }
private ICollection<Post> Posts
{
get => LazyLoader.Load(this, ref _posts);
set => _posts = value;
}
}
public class Post
{
private Blog _blog;
private Post(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
private ILazyLoader LazyLoader { get; set; }
private int Id { get; set; }
private Blog Blog
{
get => LazyLoader.Load(this, ref _blog);
set => _blog = value;
}
}
public class BloggingContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Blog>(b =>
{
b.Property("Id");
b.HasMany<Post>("Posts").WithOne("Blog");
});
builder.Entity<Post>(b =>
{
b.Property("Id");
});
}
}
Now the navigation properties are private and will lazy-load.
To the second part of your question, "produce query output with not mapped properties, calculated on navigations loaded inside entity and some business logic." I guess that depends on what you mean by "query output". Often LINQ queries that use un-mapped properties cannot be translated to SQL and will instead be evaluated on the client.
@ajcvickers all samples about lazy loading you provided exactly repeat documentation. But there is no explanation that we can't use injected ILazyLoader in any way that you can imagine. Idea to hide navigations was not to simply make it private but to use it in unmapped properties and avoid context.Blog.Include("Posts"). My thoughts were: "if we can use lazy loading inside entity why not to hide navigations, avoid context includes and provide clear business objects, with properties, that loads all the necessary data while querying".
private ICollection<Post> Posts
{
get => LazyLoader.Load(this, ref _posts);
set => _posts = value;
}
[NotMapped]
public ICollection<SomeDto> PostData
{
get
{
return Posts.Select(x => new SomeDto{ id = x.id });
}
}
So i realized that we can't do it in this way and can't use ILazyLoader in not mapped properties even if this could happens with client evaluation.
@vsopko ILazyLoader is a service for loading navigation properties. It won't work without a navigation property. You can inject the DbContext into your class if you want--just add a DbContext constructor parameter, like the ILazyLoader example above. Even with that I don't fully understand what "loads all the necessary data while querying" means, so I don't know if this will help. Also, it's generally considered bad practice to couple entity types directly to data layer concerns.