Multiple Includes() in EF Core

后端 未结 8 2147
傲寒
傲寒 2020-12-08 08:07

I have an extension method that lets you generically include data in EF:

public static IQueryable IncludeMultiple(this IQueryable          


        
相关标签:
8条回答
  • 2020-12-08 08:51

    Ofcourse there is,

    you could traverse the Expression tree of original params, and any nested includes, add them as

     .Include(entity => entity.NavigationProperty)
     .ThenInclude(navigationProperty.NestedNavigationProperty)
    

    But its not trivial, but definitely very doable, please share if you do, as it can defintiely be reused!

    0 讨论(0)
  • 2020-12-08 08:53

    You can do something like this:

    public Patient GetById(int id, Func<IQueryable<Patient>, IIncludableQueryable<Patient, object>> includes = null)
            {
                IQueryable<Patient> queryable = context.Patients;
    
                if (includes != null)
                {
                    queryable = includes(queryable);
                }
    
                return  queryable.FirstOrDefault(x => x.PatientId == id);
            }
    
    var patient = GetById(1, includes: source => source.Include(x => x.Relationship1).ThenInclude(x => x.Relationship2));
    
    0 讨论(0)
提交回复
热议问题