我目前使用 Entity Framework Core 技术,其效果非常好。然而,我正在尝试优化我的应用程序,以便在查询时从数据库返回计算数据。我正在使用 Code First 技术,其中每个模型直接映射到单个表。
以下是我持久化模型的简化示例:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<UserRole> Roles { get; set; }
}
public class UserRole
{
public int Id { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public string Role { get; set; }
}
我现在使用的是规范模式的变体,使我能够在执行查询之前运行可变数量的
.Include / .ThenInclude
。然而,我想要做的是有条件地启用投影的特定部分。例如,这是我的领域模型的样子:
public class UserImpl
{
public User User { get; set; }
public int? RoleCount { get; set; }
public static Expression<Func<User, UserImpl>> Projection(UserImplParams opts) {
return u => new UserImpl
{
User = u,
RoleCount = opts != null && opts.IncludeRoleCount ? u.Roles.Count() : default(int?)
};
}
}
public class UserImplParams
{
public bool IncludeRoleCount { get; set; }
}
我希望实现的是类似于以下方式的操作:
var opts= new UserImplParams
{
IncludeUserRole = true
};
await _databaseContext.Users.Select(UserImpl.Projection(opts)).ToListAsync();
我希望EF Core能够看到以下两种情况之一:
u => new UserImpl
{
User = u,
RoleCount = u.Roles.Count()
};
或者
u => new UserImpl
{
User = u,
RoleCount = default(int?)
};
这是可能的吗?主要是因为此表达式可能包含多个投影属性,甚至包含嵌套的属性。每次仅针对少量数据将整个表达式发送到数据库似乎效率低下。
UserImplParams
是什么并不重要,只是为了完整起见而添加。我们的思路是如何构建动态表达式?我需要实现一个表达式访问器吗? - Eliott Robson