使用 EF 和 Linq 并在 select 语句中排除属性



这些方法是通过VS2012和C#中的Entity Framework和Linq创建的,因此,我想将一个名为 Categories 的模型称为 。每个类别都有一个parentID(null 或 set),用于多重性。因此,我们有 1 个父类别,该类别具有类别的子类别,一个

System.Data.Objects.DataClasses.EntityCollection<< Category >>

但是,每个类别都有一个包含大量数据的属性,我们只想在父类别上加载该特定属性。当前代码为:

selectedCategory = categoryObjectContext.Category.Single<Category>(cat => cat.CategoryID == selectedID);
您需要

使用 .Select() 投影查询的结果,并使用 Where() 子句筛选数据:

int parentID = categoryObjectContext.Category.Where(cat => cat.CategoryID == selectedID)
                   .Select(cat => cat.parentID) // Project the query results into a single field
                   .First(); // This will only select one column

最新更新