C# 扩展SqlMethods。是否支持属性名

C# 扩展SqlMethods。是否支持属性名,c#,linq-to-sql,C#,Linq To Sql,我正在尝试扩展SqlMethods。与支持属性名称而不是属性值的方法类似,我编写了以下扩展方法: public static bool Like(this object obj, string propertyName, string pattern) { var properties = obj.GetType().GetProperties().Select(p => p.Name); if(!properties.Contai

我正在尝试扩展SqlMethods。与支持属性名称而不是属性值的方法类似,我编写了以下扩展方法:

        public static bool Like(this object obj, string propertyName, string pattern)
    {
        var properties = obj.GetType().GetProperties().Select(p => p.Name);

        if(!properties.Contains(propertyName))
            throw new Exception(string.Format("Object does not contain property:{0}", propertyName));

        return SqlMethods.Like(obj.GetType().GetProperty(propertyName).GetValue(obj, null).ToString(), pattern);
    }
但是,该方法引发以下异常: 方法“Boolean-Like(System.Object、System.String、System.String)”不支持转换为SQL


如何编写支持transaction-to-SQL的扩展方法?

与SqlMethods.Like实际做的事情相比,您想做的事情似乎没有意义。当您传入一个类的属性时,实际上是在告诉它将其转换为SQL查询中的Equivalent字段。e、 g

var result = from names in db.Names
             where SqlMethods.Like(names.FullName, '%Smith%')
             select names;
将转换为如下内容:

SELECT * 
FROM Names
WHERE Fullname LIKE '%Smith%'
(在实践中,使用参数和sp_executeSQL可能会有所不同,但从概念上讲,这就是它要做的)

如果您想传递属性的名称,那么这在SQL中意味着什么,从概念上讲它没有意义,例如

SELECT * 
FROM Names
WHERE --what would go here-- LIKE '%Smith%'
因此,您将无法创建创建无意义SQL的LINQtoSQL方法

你到底想做什么,很可能是你完全走错了路


编辑:嗯,从你的评论中,我想我理解你想要做什么,本质上你希望能够指定你在运行时做类似比较的列。你不能完全做到这一点。您可以使用使用动态SQL并为列获取字符串参数的存储过程。然后,您可以将其作为数据上下文类中的一个方法公开。

我从RichardD那里找到了这个答案,这正是正确的答案。为清晰起见,重新发布,但原文链接如下

using System;  
using System.Linq;  
using System.Linq.Expressions;  

public static class Extensions  
{  
    public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, string propertyName, string pattern)  
    {  
        if (null == source) throw new ArgumentNullException("source");  
        if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");  

        var a = Expression.Parameter(typeof(T), "a");  
        var prop = Expression.Property(a, propertyName);  
        var body = Expression.Call(typeof(SqlMethods), "Like", null, prop, Expression.Constant(pattern));  
        var fn = Expression.Lambda<Func<T, bool>>(body, a);  

        return source.Where(fn);  
    }  
}  
...  
.WhereLike("Description", "%a%b%c%"));  
使用系统;
使用System.Linq;
使用System.Linq.Expressions;
公共静态类扩展
{  
公共静态IQueryable WhereLike(此IQueryable源、字符串属性名称、字符串模式)
{  
如果(null==source)抛出新的ArgumentNullException(“source”);
if(string.IsNullOrEmpty(propertyName))抛出新的ArgumentNullException(“propertyName”);
var a=表达式参数(类型(T),“a”);
var prop=Expression.Property(a,propertyName);
var body=Expression.Call(typeof(SqlMethods),“Like”、null、prop、Expression.Constant(pattern));
var fn=表达式λ(主体,a);
返回源。其中(fn);
}  
}  
...  
.其中类似(“说明”,“a%b%c%”);
该解决方案使用表达式树,但所有高级LinqToSql操作都需要熟悉它


发件人:

可能的答案是:你不能。抱歉,替换--此处的内容--列名为terms of SQL!,这就是我需要的。这是否适用?