I have several methods that need the same lines of code
var entity = _db.Entity.AsNoTracking()
.AsSplitQuery()
.Include(x => x.Prop1)
.Include(x => x.Prop2)
.Include(x => x.Prop3)
.Include(x => x.Prop4)
.FirstOrDefault(x => x.Id == id);
is there a way to take these Includes to a method which I can call like that?
var entity = _db.Entity.AsNoTracking()
.AllIncludes()
.FirstOrDefault(x => x.Id == id);
I know about extension methods on IEnumerable but I did not find anything like what I seek
CodePudding user response:
You can achieve this by writing an extension method, which will allow you to "add" an AllIncludes
method on top of the database entity.
This will allow you to encapsulate the .Include
calls.
Assuming _db.Entity
is of type IQueryable<Entity
:
public static class QueryableExtensions
{
public static IQueryable<Entity> AllIncludes(this IQueryable<Entity> source)
{
return source
.Include(x => x.Prop1)
.Include(x => x.Prop2)
.Include(x => x.Prop3)
.Include(x => x.Prop4);
}
}
Call, as expected:
var entity = _db.Entity.AsNoTracking()
.AllIncludes()
.FirstOrDefault(x => x.Id == id);
CodePudding user response:
You can write an extension method where you invoke all of these "includes" and then return the object. Refer to the comment to your question for example extension.