仅从 Entity Framework Core 中包含的表中选择特定列

Mat*_*und 10 entity-framework entity-framework-core

如果我有这个

var selectedEntities = db.MyEntities.Include(item => item.RelatedEntities);
Run Code Online (Sandbox Code Playgroud)

它将加载 MyEntities 中的所有属性(列),以及 ReleatedEntities 中的所有属性。如果我只需要相关实体中的一个属性,我将如何指定它?

小智 4

使用 .Select() 和匿名类型来限制您想要的列

var result = await _appDbContext.Companies
            .AsNoTracking()
            .Select(company => new
            {
                Company = company,
                EmployeeIds = company.Employees.Select(emp => emp.Id)
            })
            .ToListAsync()
            .ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)