【问题标题】:C# Entity Framework filtering with .Where()使用 .Where() 进行 C# 实体框架过滤
【发布时间】:2016-08-03 03:10:07
【问题描述】:

我正在使用实体框架在 C# 中工作,我正在尝试过滤联系人查询以获取具有相同 ID 的所有联系人。我可以得到所有Contacts,但我在使用Where 进行过滤时遇到问题。我知道有问题,但我不能完全确定它,任何帮助将不胜感激。

见下方相关代码:

public IEnumerable<model.Contact> Execute(GetContactById parameters)
{
    IEnumerable<model.Contact> ContactsById = null;

    DbRetryHandler.RetryHandler(delegate(DeviceModelContext retryContext)
    {
        ContactsById = retryContext.Contact
                    .Where(c => c.Id.equals(parameters.Id))
                    .Select(c => new model.Contact
                     {
                         // unrelated code
                     });
                });

                return ContactsById;
}

【问题讨论】:

  • parameters.Id 数据类型是什么?
  • 您遇到异常了吗?您是否尝试使用== 而不是Equals
  • @YacoubMassad 是的,我已经尝试过了,结果仍然为空。我可以看到当我使用断点运行它时 c.Id 永远不会获得值,所以最终它只是将 parameters.Id 与 Null 进行比较。
  • @Ian parameters.Id 是一个 Guid。
  • @FrederikPetersen 您不应该更改原始问题并使用可行的解决方案对其进行更新,因为在同一问题中运行的其他程序员无法跟进最初的错误。这就是答案的目的。请将其恢复到原始状态(未运行的代码)

标签: c# entity-framework filtering


【解决方案1】:

提供程序在识别无法转换为 SQL 的表达式时遇到问题。尽量简化表达式,以便更容易地转换为 SQL。

public IEnumerable<model.Contact> Execute(GetContactById parameters)
{
     IEnumerable<model.Contact> ContactsById = null;
     DbRetryHandler.RetryHandler(delegate(DeviceModelContext retryContext)
     {
         var parametersId = parameters.Id; // <-- store id in variable
         camerasByDeviceId = retryContext.Contact
           .Where(c => c.Id == parametersId) // <-- use == instead of Equals
           .Select(c => new model.Camera
           {
               // unrelated code
           });
     });

     return ContactsById;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2019-04-14
    • 2017-11-08
    • 2022-01-23
    • 2014-12-19
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多