【问题标题】:Unexpected behavior of the `Where` clause`Where` 子句的意外行为
【发布时间】:2016-02-15 07:53:50
【问题描述】:

我有以下 Linq 语句,用于检索表中满足特定条件的所有行的列表。

var set = db.TcSet
    .Where(x => x.SetName.Equals(original.SetName))
    .AsEnumerable()
    .Where(x => x.SetName == original.SetName))

此特定语句用于编辑表中具有特定名称的所有实体。因此,在original 中检索属性的初始名称,并检查数据库中与条件匹配的所有其他条目。

电流输出

如果我有两个名为 Play123 的条目并编辑其中一个条目,则 where query 的输出仅包含一个元素。

如果有一个条目Play123Play1234,并且我尝试将Play123 编辑为Play1234,则where query 的输出包含两个元素:Play123Play1234

我遗漏了什么会导致这种意外行为。

更新

var original = db.TcSet.Find(tcSet.TcSetID);
foreach (var set in db.TcSet
    .Where(x => x.SetName.Equals(original.SetName))
    .AsEnumerable()
    .Where(x => x.SetName == original.SetName)))
{
    if (set.SetName == original.SetName) // This was added again due to the unexpected behavior
    {
           set.ModifiedBy = User.Identity.Name;
           set.ModifiedOn = DateTime.Now;
           set.PhysicalUnit = tcSet.PhysicalUnit;

           db.Entry(set).State = EntityState.Modified;

           db.Entry(set).Property(x => x.CreatedBy).IsModified = false;
           db.Entry(set).Property(x => x.CreatedOn).IsModified = false;
           db.Entry(set).Property(x => x.TechnicalCharacteristicID).IsModified = false;
    }      

}

现在我通过遍历表中的所有元素解决了这个问题,我知道这不是最佳做法。

工作代码

   var editlist = db.TcSet.Where(x => x.SetName == original.SetName).AsEnumerable().Where(x=>x.SetName==original.SetName).ToList();

  foreach(var set in editlist)
      // do save

当我删除 if 条件时,它起作用了。

【问题讨论】:

  • 如何编辑条目?
  • 我们可能需要更多代码才能更好地了解您正在尝试做什么。
  • 我将在代码中添加编辑控制器逻辑..
  • 你可以使用这样的地方我可能会帮助你 'db.TcSet.Where(x => x.SetName.toLower().Count(original.SetName)) .AsEnumerable().Where( x=> x.SetName.toLower().Count(original.SetName))'
  • @ImranLuhur:这不是预期的行为。我需要区别对待ABCabc。我在AsEnumerable 之后的where 就是为了达到这个目的。

标签: c# mysql asp.net-mvc linq


【解决方案1】:

如果您要区别对待 abcABC,您希望在第一个 .Where() 子句中进行不区分大小写的检查。

var set = db.TcSet
    .Where(x => x.SetName.Equals(original.SetName, StringComparison.OrdinalIgnoreCase));

我还建议在 foreach 中迭代之前缓存结果,因为您要在迭代时更改源列表,这绝不是一个好主意。

var original = db.TcSet.Find(tcSet.TcSetID);
var sets = db.TcSet
    .Where(x => x.SetName.Equals(original.SetName, StringComparison.OrdinalIgnoreCase))
    .ToList();

foreach (var set in sets)
{
   set.ModifiedBy = User.Identity.Name;
   set.ModifiedOn = DateTime.Now;
   set.PhysicalUnit = tcSet.PhysicalUnit;

   db.Entry(set).State = EntityState.Modified;

   db.Entry(set).Property(x => x.CreatedBy).IsModified = false;
   db.Entry(set).Property(x => x.CreatedOn).IsModified = false;
   db.Entry(set).Property(x => x.TechnicalCharacteristicID).IsModified = false;
}

【讨论】:

    猜你喜欢
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多