代码之家  ›  专栏  ›  技术社区  ›  Baz1nga

数据库上的Linq查询和使用自定义比较器

  •  0
  • Baz1nga  · 技术社区  · 14 年前

    在Linq查询中使用自定义比较器有什么用?它们是有益的还是只是服务器上的超载。

    IEnumerable<Class> GetMatch(Class comparerObject)
    {
      return  Session.Linq<Class>().Where(x=>new StringComparer<Class>().Equals(x,comparerObject))
    }
    

    这就是我的stringcomparer类的样子

    public class StringComparer<T> : IEqualityComparer<T>
        where T : class, IStringIdentifiable
    {
        public bool Equals(T x, T y)
        {
            if (x == null && y == null)
                return true;
    
            if (x == null || y == null)
                return false;
    
            return x.Id.Equals(y.Id, StringComparison.OrdinalIgnoreCase);
        }
    

    所以我想知道这个查询是如何针对数据库运行的?我认为linq在内部处理这个问题,其中只有在comparere中的所有案例运行之后,linq才会向db发送请求。

    如果你很难相信上面的方法是行不通的,那么举个简单的例子

    return  Session.Linq<Class>().Where(x=>x.Id.Equals(comparerObject,StringComparison.InvariantCultureIgnoreCase))
    

    谢谢。

    1 回复  |  直到 14 年前
        1
  •  1
  •   Jon Skeet    14 年前

    对于LINQ-to-SQL,我希望在执行时失败-查询转换程序不知道如何处理 StringComparer<T>

    如果你已经给出了,你应该使用:

    string idToMatch = comparerObject.Id;
    return Session.Linq<Class>().Where(x => x.Id == idToMatch);
    

    更复杂的情况可能可行,也可能不可行,这取决于 确切地 你想达到的目标。