首页 > 解决方案 > 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)
});

当我执行投影时,它将正常工作ProductImages。但是对于Category生成的 SQL 将包含所有列(IdCategoryName)。

标签: c#linqlinq-to-sqlentity-framework-core

解决方案


推荐阅读