7

データベースにアクセスするための小さなフレームワークを開発しています。ラムダ式を使用してクエリを作成する機能を追加したいと考えています。どうすればいいですか?

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 プロバイダーを作成します(とにかく、これをやりたくないはずです)。

たいへんな作業なので、単にNHibernateEntity Frameworkなどを使いたいだけかもしれません。

クエリがかなり単純な場合は、本格的な 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 に答える