【问题标题】:linq query for varchar field not returning any results对 varchar 字段的 linq 查询不返回任何结果
【发布时间】:2012-12-19 10:51:59
【问题描述】:

当我在 linqpad 中运行此查询时:

Customer.Where(c => (c.CustomerName == "test"))

它返回匹配的记录。

当我尝试在 visual studio 中运行相同的查询时,它不会返回任何匹配的记录。这是我正在使用的代码:

    List<Customer> customerList = new List<Customer>();

    using (DBEntities db = new DBEntities())
    {
        try
        {
            customerList = db.Customer.Where(c => (c.customerName == "test")).ToList();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    return customerList;

谁能明白为什么它在 linqpad 中有效,但在 visual studio 中无效?

【问题讨论】:

  • 如果你调试,db.Customer 对象中是否有一堆对象,其中至少有一个带有“test”作为customerName?它看起来很简单,这是最简单的问题。
  • 您的 VS 代码中有不同的 customerName 大小写。我不知道这是否只是一个错字。此外,new List&lt;Customer&gt;() 分配是多余的,因为它会被查询覆盖。
  • linqpad 对象名大写,VS 不改。

标签: c# linq visual-studio linqpad


【解决方案1】:

你可以这样试试吗

customerList = db.Customer.
   Where(c => String.Compare (c.customerName.ToUpper(),"test".ToUpper()) == 0).ToList();

因为客户姓名的区分大小写搜索可能存在问题。

根据需要尝试其他变体:String.Compare Method

【讨论】:

    【解决方案2】:

    您的 linqpad 查询使用“c.CustomerName”,而您的 Visual Studio 查询使用“c.customerName”。

    另外,您的问题可能是它区分大小写,或者 db.Customer 集为空。

    编辑: DeeMac 在他的回复中也提到了这一点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多