My issue is that EF Core is by default loading all my defined properties of a class, whereas I want it to not load them unless I specifically ask for them.
For example, take this simple example of a book with an author (all models are the same in this example but just to show the pattern used):
Database entity:
using System;
namespace Test.Models.DBModels
{
public partial class Book
{
public int BookId { get; set; }
public int AuthorId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
}
}
DTO:
using System;
using System.Collections.Generic;
namespace Test.Models.DTOModels
{
public partial class BookDTO
{
public int BookId { get; set; }
public int AuthorId { get; set; }
public string Title { get; set; }
public AuthorDTO Author { get; set; }
}
}
ViewModel:
using System;
using System.Collections.Generic;
namespace Test.Models.ViewModels
{
public partial class BookVM
{
public int BookId { get; set; }
public int AuthorId { get; set; }
public string Title { get; set; }
public AuthorVM Author { get; set; }
}
}
Notice there is no use of "virtual" properties on any of these classes as I'd read that this is what told EF to automatically populate them
DBContext:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Test.Models.DBModels;
namespace Test.DAL
{
public partial class TestContext : DbContext
{
public TestContext()
{
}
public TestContext(DbContextOptions<TestContext> options)
: base(options)
{
}
public virtual DbSet<Author> Author { get; set; }
public virtual DbSet<Book> Book { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//optionsBuilder.UseSqlServer("connectionstring");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
Service:
using AutoMapper;
using System.Collections.Generic;
using System.Linq;
using Test.BLL.Interfaces;
using Test.DAL;
using Test.Models.DomainModels;
using Test.Models.DTOModels;
using Microsoft.EntityFrameworkCore;
using AutoMapper.QueryableExtensions;
using System.Linq.Expressions;
using System;
namespace Test.BLL.Implementations
{
public class BookService : IBookService
{
private readonly TestContext dbContext;
private readonly IMapper _mapper;
public BookService(TestContext dbContext, IMapper mapper)
{
this.dbContext = dbContext;
this._mapper = mapper;
}
public IQueryable<BookDTO> Get()
{
var books = dbContext.Book;
var dto = books.ProjectTo<BookDTO>(_mapper.ConfigurationProvider);
return dto;
}
public IQueryable<BookDTO> Get(params Expression<Func<Book, object>>[] includes)
{
var books = dbContext.Book
.Select(x => x);
foreach (var include in includes)
books = books.Include(include);
var dto = books.ProjectTo<BookDTO>(_mapper.ConfigurationProvider);
return dto;
}
}
}
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Test.BLL.Implementations;
using Test.Models.DTOModels;
using Test.Models.ViewModels;
namespace Test.WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BookController : ControllerBase
{
private readonly BookService BookService;
private readonly IMapper _mapper;
public BookController(BookService BookService, IMapper mapper)
{
this.BookService = BookService;
this._mapper = mapper;
}
public IActionResult Index()
{
var books = _mapper.Map<IEnumerable<BookDTO>, IEnumerable<BookVM>>(BookService.Get().ToList());
return Ok(books);
}
}
}
If I call the BookService.Get().ToList() method in the controller then it is automatically populating the Author in the json results e.g.
{
"bookId":1,
"authorId":1,
"title":"Book A",
"author":{
"authorId":1,
"name":"Some Author"
}
}
Whereas I only want it to be:
{
"bookId":1,
"authorId":1,
"title":"Book A",
"author": null
}
As if I wanted the Author object populated I'd call my overloaded method using BookService.Get(x => x.Author).ToList()
I assume this is related to eager or lazy loading functionality, but I'm not sure how. EDIT: The documentation describes them as "Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed". They also say that "Eager loading means that the related data is loaded from the database as part of the initial query" which is the behavior I want, but only for the properties I specify.
Is there a way in EF Core that I can get it to only populate the properties if I am specifically requesting them to be included?
Select()
to retrieve specific properties, you only get those properties. – Panagiotis Kanavos Mar 4 '20 at 12:45I'd read that this is what told EF to automatically populate them
it's the exact opposite. You can't use lazy loading unless the related entities arevirtual
. This allows the ORM to generate a proxy class that will load the related entities from database when requested. – Panagiotis Kanavos Mar 4 '20 at 12:48ProjectTo
method. What is that, what does it do? If you wanted only specific properties, a simple.Select(bool=>new {book.BoodId, book.Title})
would do. That's the benefit of using LINQ. And what using – Panagiotis Kanavos Mar 4 '20 at 12:59