【问题标题】:Ef Core Table relationship include count ErrorEf Core Table 关系包括计数错误
【发布时间】:2021-07-31 08:02:48
【问题描述】:

我是使用 .NET 和 EF Core 的新手。我无法计算与 post 表关联的 like 表。

我要做的是显示帖子上的总喜欢数。

PostManager:

var posts = await _unitOfWork.Posts
                             .GetAllAsync(p => p.UserId == userId && 
                                               p.IsActive == true, 
                                          l => l.Likes.Count()); 

EfBaseRepository:

public async Task<IList<TEntity>> GetAllAsync(Expression<Func<TEntity, bool>> predicate = null, params Expression<Func<TEntity, object>>[] includeProperties)
{
        IQueryable<TEntity> query = _context.Set<TEntity>();

        if (predicate != null)
        {
            query = query.Where(predicate);
        }

        if (includeProperties.Any())
        {
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
        }

        return await query.ToListAsync();
}

错误:

System.InvalidOperationException:表达式“Convert(l.Likes.AsQueryable().Count(), Object)”在“包含”操作中无效,因为它不代表属性访问:“t => t 。我的财产'。要定位在派生类型上声明的导航,请使用强制转换 ('t => ((Derived)t).MyProperty') 或 'as' 运算符 ('t => (t as Derived).MyProperty')。集合导航访问可以通过组合 Where、OrderBy(Descending)、ThenBy(Descending)、Skip 或 Take 操作进行过滤。有关包含相关数据的更多信息,请参阅http://go.microsoft.com/fwlink/?LinkID=746393

【问题讨论】:

    标签: c# entity-framework-core ef-code-first


    【解决方案1】:

    如果您是 EF Core 新手,请不要创建通用存储库,这是无用的模式,只会增加复杂性。

    正确和最快的查询是:

    var likesCount = await _context.Posts
       .Where(p => p.UserId == userId && p.IsActive == true)
       .SelectMany(p => p.Likes)
       .CountAsync(); 
    

    【讨论】:

      【解决方案2】:

      改为这样做。基本上,您要实现“延迟加载”。在您的“GetAllAsync”方法中,“includeProperties”需要一个属性。在这种情况下,“喜欢”属性是“l.Likes”而不是“l.Likes.Count()”。之后你可以数数。

      var posts = await _unitOfWork.Posts
                               .GetAllAsync(p => p.UserId == userId && 
                                                 p.IsActive == true, 
                                            l => l.Likes).ToListAsync(); 
      var likesCount = posts.Likes.Count();
      

      【讨论】:

      • 很遗憾,我无法通过帖子访问喜欢的内容。你说的方法不行
      • @EmreŞimşek 你绝对可以。我添加了“.ToListAsync()”。我猜这是因为你把它作为“IList”
      猜你喜欢
      • 2018-05-06
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2018-11-08
      • 2021-05-20
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      相关资源
      最近更新 更多