EF Code First Distity with Distinct()

时间:2014-04-07 12:18:42

标签: linq entity-framework ef-code-first

我对下面的代码有些不太了解。我正在尝试找到模块集合中有重复模块的worker。

这是实体(为简洁起见而简化):

public class Worker
{
    public int Id { get; private set; }
    public ICollection<TakenTrainingModule> TakenTrainingModules { get; private set; }

    public Worker()
    {
        TakenTrainingModules = new HashSet<TakenTrainingModule>();
    }
}

public class TakenTrainingModule
{
    public int Id { get; set; }
    public int TrainingModuleId { get; set; }
}

这是查询:

var query = from worker in _context.Workers.Include(worker => worker.TakenTrainingModules)
            let distinctModules = worker.TakenTrainingModules.Select(module => module.TrainingModuleId).Distinct()
            where worker.TakenTrainingModules.Count != distinctModules.Count()
            select worker;

使用下面的查询,返回的工作人员将其TakenTrainingModules集合清空。

但是,使用下一个查询(不使用keywork let),该集合已完全正确加载:

var query = from worker in _context.Workers.Include(worker => worker.TakenTrainingModules)
            where worker.TakenTrainingModules.Count != worker.TakenTrainingModules.Select(module => module.TrainingModuleId).Distinct().Count()
            select worker;

我错过了什么? let关键字是第一次执行不同的查询并欺骗对象状态管理器,模块已加载但它们不是,并且选择器不会加载它们吗?

欢迎任何解释! : - )

1 个答案:

答案 0 :(得分:0)

我已将查询更新为:

var query = from worker in _context.Workers
            let distinctModules = worker.TakenTrainingModules.Select(module => module.TrainingModuleId).Distinct()
            where worker.TakenTrainingModules.Count != distinctModules.Count()
            select worker;

return query.Include(worker => worker.TakenTrainingModules).ToArray();

一切都很好。感谢Dismissile给我一个很好的答案。