如何使用Dapper与Linq [英] How to use Dapper with Linq

查看:2543
本文介绍了如何使用Dapper与Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我使用的查询是像谓词表达式这样的谓词形式,因此我正在尝试将Entity Framework转换为Dapper,以提高数据访问性能。 >。



举个例子:



我有以下代码,我需要转换为使用dapper。



我目前所做的:

  public async Task&列表与LT; TModel的>> Get(Expression< Func< TModel,bool>>查询)
{
// this.Context的类型为DbContext
return await this.Context.Set< TModel>() (查询).ToListAsync();
}

我想做什么:

  public async任务< List< TModel>> Get(Expression< Func< TModel,bool>>查询)
{
using(IDbConnection cn = this.GetConnection)
{
return await cn.QueryAsync< TModel&查询);
}
}

我的google-fu失败了,有人可以请



编辑:



请注意,我确实发现:
但我似乎无法弄清楚如何使用它。

首先,作者之一的Dapper说,当有人问


有没有计划让Dapper.net与IQueryable接口兼容?



没有计划这样做。它远远超出了dapper试图做的事情。到目前为止,我会说这是对立的。 Dapper核心试图成为那些爱他们的SQL的朋友。


(请参阅 https://stackoverflow.com/a/27588877/3813189 )。



在某种程度上,这表明NuGet的各种扩展包可能会有所帮助,如您所建议的。



我尝试过 DapperExtensions ,这使得以编程方式编写查询过滤器更容易一些 - 例如。

 code>使用System.Data.SqlClient; 
使用DapperExtensions;

命名空间StackOverflowAnswer
{
类程序
{
static void Main(string [] args)
{
using var cn = new SqlConnection(Server =; Database = NORTHWND; Trusted_Connection = True;))
{
var list = cn.GetList< Products>(
Predicates.Field< Products> ;(f => f.Discontinued,Operator.Eq,false)
);
}
}

class产品
{
public int ProductId {get;组; }
public string ProductName {get;组; }
public bool Discontinued {get;组; }
}
}
}

我也尝试过 Dapper.Extensions.Linq (您建议的包),它承诺


建立在此基础上,通过Linq查询提供高级数据库访问。流体配置使设置变得简单快速。


不幸的是,我也不能很远。没有太多的文档,测试似乎没有涵盖QueryBuilder,这似乎是用于将Linq表达式转换为Dapper Extensions谓词的类(如问题使用QueryBuilder解析布尔表达式)。我尝试以下,这需要添加IEntity接口到我的DTO -

 使用系统; 
使用System.Data.SqlClient;
使用System.Linq.Expressions;
使用Dapper.Extensions.Linq.Builder;
使用Dapper.Extensions.Linq.Core;
使用DapperExtensions;

命名空间StackOverflowAnswer
{
类程序
{
static void Main(string [] args)
{
using var cn = new SqlConnection(Server =; Database = NORTHWND; Trusted_Connection = True;))
{
表达式< Func< Products,bool>> filter = p => !p.Discontinued;
var queryFilter = QueryBuilder< Products> .FromExpression(filter);

var list = cn.GetList< Products>(
queryFilter
);
}
}

class产品:IEntity
{
public int ProductId {get;组; }
public string ProductName {get;组; }
public bool Discontinued {get;组; }
}
}
}

..但它失败在运行时出现错误


没有找到运算符StackOverflowAnswer.Program +产品


我不知道为什么手动生成Predicate(第一个例子),但是QueryBuilder没有。



我会说,它越来越看起来像你的问题留下的评论是正确的,你将需要重新工作的代码远离您使用Entity Framework的表达式。由于找到有关此QueryBuilder类的任何信息非常困难,所以我会担心(即使您确实可以正常工作)遇到的任何问题都难以获得帮助(而且错误可能会不成功)。 p>

I'm trying to convert from Entity Framework to Dapper to hopefully improve data access performance.

The queries I use are in the form of predicates like so "Expression>".

To give an example:

I have the following code which I need to convert to using Dapper.

What I currently do:

public async Task<List<TModel>> Get(Expression<Func<TModel, bool>> query)
{
    // this.Context is of type DbContext
    return await this.Context.Set<TModel>().Where(query).ToListAsync();
}

What I'd like to do:

public async Task<List<TModel>> Get(Expression<Func<TModel, bool>> query)
{
    using (IDbConnection cn = this.GetConnection)
    {
        return await cn.QueryAsync<TModel>(query);
    }
}

My google-fu is failing me, can someone please assist.

Edit:

Note that I did find: https://github.com/ryanwatson/Dapper.Extensions.Linq

but I can't seem to figure out how to use it.

解决方案

Firstly, one of the authors of Dapper said, when someone asked

Is there a plan to make Dapper.net compatible with IQueryable interfaces?

that

there are no plans to do this. It is far far outside what dapper tries to do. So far that I would say it is antithetical. Dapper core tries to be the friend to those who love their SQL.

(see https://stackoverflow.com/a/27588877/3813189).

In a way, that does suggest that the various extension packages to NuGet may help, as you have suggested.

I have tried DapperExtensions, which makes writing the query filters in a programmatic way a little easier - eg.

using System.Data.SqlClient;
using DapperExtensions;

namespace StackOverflowAnswer
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var cn = new SqlConnection("Server=.;Database=NORTHWND;Trusted_Connection=True;"))
            {
                var list = cn.GetList<Products>(
                    Predicates.Field<Products>(f => f.Discontinued, Operator.Eq, false)
                );
            }
        }

        class Products
        {
            public int ProductId { get; set; }
            public string ProductName { get; set; }
            public bool Discontinued { get; set; }
        }
    }
}

I also tried Dapper.Extensions.Linq (the package you suggested), which promises to

builds on this providing advanced DB access through Linq queries. The fluid configuration makes setup simplistic and quick.

Unfortunately, I also couldn't get very far with it. There isn't much documentation and the tests don't seem to cover the QueryBuilder, which is what appears to be the class to use to translate Linq Expressions into the Dapper Extensions predicates (as suggested by the issue Parsing boolean expressions with the QueryBuilder). I tried the following, which required add the IEntity interface to my DTO -

using System;
using System.Data.SqlClient;
using System.Linq.Expressions;
using Dapper.Extensions.Linq.Builder;
using Dapper.Extensions.Linq.Core;
using DapperExtensions;

namespace StackOverflowAnswer
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var cn = new SqlConnection("Server=.;Database=NORTHWND;Trusted_Connection=True;"))
            {
                Expression<Func<Products, bool>> filter = p => !p.Discontinued;
                var queryFilter = QueryBuilder<Products>.FromExpression(filter);

                var list = cn.GetList<Products>(
                    queryFilter
                );
            }
        }

        class Products : IEntity
        {
            public int ProductId { get; set; }
            public string ProductName { get; set; }
            public bool Discontinued { get; set; }
        }
    }
}

.. but it failed at runtime with the error

Operator was not found for StackOverflowAnswer.Program+Products

I'm not sure why generating the Predicate manually (the first example) works but the QueryBuilder doesn't..

I would say that it's increasingly looking like the comments left on your question are correct, that you will need to re-work your code away from the expressions that you used with Entity Framework. Since it's been so difficult to find any information about this QueryBuilder class, I would be concerned that (even if you did get it working) any issues that you encountered would be difficult to get help for (and bugs may go unfixed).

这篇关于如何使用Dapper与Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆