美好的一天,
我正在使用 linq 扩展方法,并且我有一个表,我需要从表 Courses 中提取项目列表,除了一些我不想要的类(class)。
public class Course
{
public Course()
{
Tags = new HashSet<Tag>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Level { get; set; }
public float FullPrice { get; set; }
public virtual Author Author { get; set; }
public int AuthorId { get; set; }
}
这是我到目前为止所做的:
//Get some courses that I do not need.
var coursesDontNeed=_dbContext.courses.where(//here goes condition);
var coursesINeed= _dbContext.Courses.Except(coursesDontNeed);
有什么方法可以只访问一次数据库,而不是编写两个不同的 linq 语句吗?
谢谢
最佳答案
您可以创建 LINQ 查询表达式,并且不计算/执行它,而是在第二个 LINQ 查询中使用它。
var courseIdsDontNeed= db.Courses.Where(yourWherePredicateGoesHere).Select(a => a.Id);
var coursesINeed = db.Courses.Where(p => !courseIdsDontNeed.Contains(p.Id) ).ToList();
当您在第二个 LINQ 查询上调用 ToList()
或 ToArray()
时,将执行 linq 表达式,并且只有一个 SQL 语句 (< em>它具有过滤逻辑来排除那些针对数据库生成和执行的项目。
将 yourWherePredicateGoesHere
替换为要过滤的实际谓词。例如,
var courseIdsDontNeed= db.Courses.Where(a=>a.IsActive).Select(a => a.Id);
关于c# - Linq 扩展方法 select not in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47244132/