c# - EF Core 5 单属性投影
问题描述
我想减少重复的代码。为了实现这一点,我想参考我的实体的投影。
实体
public class Category
{
public string Id { get; set; }
public string CategoryName { get; set; }
public static Expression<Func<Category, Category>> Proj() => c => new Category
{
CategoryName = c.CategoryName
};
}
public class Image
{
public string Id { get; set; }
public string Url { get; set; }
public static Expression<Func<Image, Image>> Proj() => i => new Image
{
Url = i.Url
};
}
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public ICollection<Image> Images { get; set; }
public Category Category { get; set; }
}
投影查询
var categoryProjection = Category.Proj().Compile();
var products = _ctx.Products.Select(p => new Product
{
Id = p.Id,
Name = p.Name,
Images = p.Images.AsQueryable().Select(Image.Proj()).ToHashSet(),
Category = categoryProjection.Invoke(p.Category)
});
当我执行投影时,它将正常工作Product
和Images
。但是对于Category
生成的 SQL 将包含所有列(Id
和CategoryName
)。
解决方案
推荐阅读
- java - 无法设置 JAVA_HOME GitLab CI
- database - PostreSQL 10 无法在 Linux 的 Windows 子系统上运行的 Ubuntu 18.04 上启动
- peoplesoft - SQR 过程参数/参数
- git - 重置我的最后一次提交撤消许多提交
- python - 如何重新调整 fft 点以获得与解析解相同的结果?
- javascript - 时刻js更改日期时间的日期部分
- sqlite - 如何计算表中的时间差 HH:MM?
- javascript - 显示表格内的数据
- python - 检查列表的任何字符串是否出现在更大的字符串上
- batch-file - 将所有单词连接到批处理中的同一行后如何在单词之间保留空格