EF核心-使用投影并包含实体集合

时间:2020-05-20 14:01:08

标签: c# asp.net-core ef-core-2.2

我有一个基本存储库:

prompt = "\nI will price your ticket. What is your age?"

active = True #Per Matthes, using the flag Active, a program "should run while 
#the flag is set to True and stop running when any of several events sets the 
#value of the flag to False."  
while active:
    message = int(input (prompt))

    if message < int(3):
        print("Your ticket is free!")
    elif int(3) <= message <= int(12):
        print("Your ticket is $10!")
    elif message > int(12):
        print("Your ticket is $15!")
    else:
        active = False
        break #Per Matthes, the break statement will force the program "to exit
        #a while loop immediately without running any remaining code in the 
        #loop." 

我尝试获取业务实体,并包含image.inverseParents,但没有成功:

public async Task<TEntity> GetByCondition(Expression<Func<TEntity, bool>> predicate, Func<DbSet<TEntity>, IQueryable<TEntity>> baseQuery = null, Expression<Func<TEntity, TEntity>> projection = null)
{
    IQueryable<TEntity> q = _context.Set<TEntity>();

    if (baseQuery != null)
    {
        q = baseQuery(_context.Set<TEntity>());
    }

    q = q.Where(predicate);

    if (projection != null)
    {
        q = q.Select(projection);
    }

    return await q.FirstOrDefaultAsync();
}

我该怎么做才能工作?
Expression<Func<Businesses, bool>> predicate = x => x.Id == id; Expression<Func<Businesses, Businesses>> projection = x => new Businesses { BusinessImages = x.BusinessImages .Where(bi => bi.Status == (int)EnumGringo.LU_Status.active && bi.Image.Status == (int)EnumGringo.LU_Status.active) .Select(bi => new BusinessImages { //Won't complie Image = bi.Image.Include(i=>i.InverseParent) }).ToList() }; Businesses business = await _repository.GetByCondition(predicate, projection: projection);

我尝试过的事情:
Image = bi.Image.Include(i=>i.InverseParent)

添加

Image = bi.Image.Select(i=>i.InverseParent.Parent).FirstOrDefault()

基本存储库会忽略基本查询。

1 个答案:

答案 0 :(得分:0)

投影查询将忽略Include,一旦您选择了Select,就需要继续进行全选。

这对我有用:

 BusinessImages = x.BusinessImages
                                  .Where(bi => bi.Status == (int)EnumGringo.LU_Status.active && bi.Image.Status == (int)EnumGringo.LU_Status.active)
                                  .Select(bi => new BusinessImages
                                  {
                                      Image = new UserImages
                                      {
                                          InverseParent = bi.Image.InverseParent
                                      }
                                  })