7

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

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

public class Repository<T>
{
    // do something.
}

例如:

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.
4

3 回答 3

16

继续并创建一个LINQ 提供程序(我相信您无论如何都不想这样做)。

这是很多工作,所以也许您只想使用NHibernate实体框架或类似的东西。

如果您的查询相当简单,也许您不需要完整的 LINQ 提供程序。查看表达式树(由 LINQ 提供程序使用)。

你可以破解这样的东西:

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);
    }
}

请不要按原样使用它。这只是一个快速而肮脏的示例,如何分析表达式树以创建 SQL 语句。

为什么不直接使用 Linq2Sql、NHibernate 或 EntityFramework...

于 2012-06-11T12:00:04.310 回答
2

如果你想做类似的事情

db.Employee
.Where(e => e.Title == "Spectre")
.Set(e => e.Title, "Commander")
.Update();

或者

db
.Into(db.Employee)
    .Value(e => e.FirstName, "John")
    .Value(e => e.LastName,  "Shepard")
    .Value(e => e.Title,     "Spectre")
    .Value(e => e.HireDate,  () => Sql.CurrentTimestamp)
.Insert();

或者

db.Employee
.Where(e => e.Title == "Spectre")
.Delete();

然后看看这个,BLToolkit

于 2012-06-11T12:42:14.093 回答
0

你可能想看看http://iqtoolkit.codeplex.com/这是非常复杂的,我不建议你从头开始构建一些东西。

我刚刚写了一些接近 dkons 答案的东西,无论如何我都会添加它。只是使用流畅的界面而已。

public class Query<T> where T : class
{
    private Dictionary<string, string> _dictionary;

    public Query()
    {
        _dictionary = new Dictionary<string, string>();
    } 

    public Query<T> Eq(Expression<Func<T, string>> property)
    {
        AddOperator("Eq", property.Name);
        return this;
    }

    public Query<T> StartsWith(Expression<Func<T, string>> property)
    {
        AddOperator("Sw", property.Name);
        return this;
    }

    public Query<T> Like(Expression<Func<T, string>> property)
    {
        AddOperator("Like", property.Name);
        return this;
    }

    private void AddOperator(string opName, string prop)
    {
        _dictionary.Add(opName,prop);
    }

    public void Run(T t )
    {
        //Extract props of T by reflection and Build query   
    }
}

假设你有一个模型

class Model
    {
        public string Surname{ get; set; }
        public string Name{ get; set; }
    }

您可以将其用作:

static void Main(string[] args)
        {

            Model m = new Model() {Name = "n", Surname = "s"};
            var q = new Query<Model>();
            q.Eq(x => x.Name).Like(x=>x.Surname).Run(m);


        }
于 2012-06-13T09:16:32.347 回答