【发布时间】: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