如何将Lambda表达式转换为Sql?

sin*_*ici 6 c# linq lambda asqueryable

我正在开发一个小框架来访问数据库.我想添加一个使用lambda表达式进行查询的功能.我该怎么做呢?

public class TestModel
{
    public int Id {get;set;}
    public string Name {get;set;}
}

public class Repository<T>
{
    // do something.
}
Run Code Online (Sandbox Code Playgroud)

例如:

var repo = new Repository<TestModel>();

var query = repo.AsQueryable().Where(x => x.Name == "test"); 
// This query must be like this:
// SELECT * FROM testmodel WHERE name = 'test'

var list = query.ToDataSet();
// When I call ToDataSet(), it will get the dataset after running the made query.
Run Code Online (Sandbox Code Playgroud)

slo*_*oth 14

继续创建LINQ提供程序(我相信你不想这样做).

这是很多工作,所以也许你只想使用NHibernateEntity Framework或类似的东西.

如果您的查询相当简单,也许您不需要一个完整的LINQ提供程序.看看Expression Trees(由LINQ Providers使用).

你可以破解这样的东西:

public static class QueryExtensions
{
    public static IEnumerable<TSource> Where<TSource>(this Repo<TSource> source, Expression<Func<TSource, bool>> predicate)
    {
        // hacks all the way
        dynamic operation = predicate.Body;
        dynamic left = operation.Left;
        dynamic right = operation.Right;

        var ops = new Dictionary<ExpressionType, String>();
        ops.Add(ExpressionType.Equal, "=");
        ops.Add(ExpressionType.GreaterThan, ">");
        // add all required operations here            

        // Instead of SELECT *, select all required fields, since you know the type
        var q = String.Format("SELECT * FROM {0} WHERE {1} {2} {3}", typeof(TSource), left.Member.Name, ops[operation.NodeType], right.Value);
        return source.RunQuery(q);
    }
}
public class Repo<T>
{
    internal IEnumerable<T> RunQuery(string query)
    {
        return new List<T>(); // run query here...
    }
}
public class TestModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var repo = new Repo<TestModel>();
        var result = repo.Where(e => e.Name == "test");
        var result2 = repo.Where(e => e.Id > 200);
    }
}
Run Code Online (Sandbox Code Playgroud)

请不要使用它.这只是一个快速而肮脏的例子,可以分析表达式树来创建SQL语句.

为什么不使用Linq2Sql,NHibernate或EntityFramework ...