I want to configure my DbContext to eager-load certain properties when calling Set<T>()
. Given the following classes:
public class Thing
{
public int Id { get; set; }
public int OtherThingId { get; set; }
public OtherThing OtherThing { get; set; }
}
public class OtherThing
{
public int Id { get; set; }
}
public class MyContext : DbContext
{
protected override void OnModelCreating( ModelBuilder modelBuilder )
{
modelBuilder.Entity<Thing>();
modelBuilder.Entity<OtherThing>();
}
}
How can I configure EF Core so that when I call:
var myThing = new MyContext().Set<Thing>().First();
then myThing.OtherThing
is not null
?
I know that if I have a context then I can use the Include
/ ThenInclude
methods to eager load particular properties when I know the type of the thing I am querying for. But I want to be able to inject a generic repository interface which knows nothing about EF, something like:
public interface IRepository
{
Task<T> GetAsync<T>( int id );
}
I want to be able to implement this interface which uses MyContext
, and then configure EF separately so that using just Set<T>()
will include whichever properties I have configured without calling those extension methods/making my interface API EF-specific?
There don't seem to be methods on ModelBuilder
which I can use to achieve this. Essentially all I want is:
modelBuilder.Entity<Thing>().Include(x => x.OtherThing);