宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

一、dapper框架优点

1、轻量级:dapper的核心代码只有带注释的500行左右,不依赖其他的扩展库,无需大量配置,非常轻量级。

2、高性能:相对于EF等ORM工具,dapper对于对象与关系库的映射采用的是动态反射的形式,所以能够用比其他ORM工具更少的时间,完成更多的数据操作。并且dapper在生成sql语句时采用了缓存池技术,能够大大减少创建对象的时间,且有很好的性能表现。

3、简单易用:dapper的API接口非常简单,不需要像NHibernate、EF等ORM工具那样有复杂的配置信息,学习成本低,能够快速上手。

二、dapper框架有必要吗

对于小型项目或者仅需进行基本的数据操作的项目来说,dapper是非常必要的,因为它轻量高效,不会给项目带来额外的负担,同时又能够快速完成数据操作。但是对于大型项目来说,需要考虑到维护的难度以及可扩展性等问题,需要慎重考虑是否使用dapper。

三、dapper框架底层实现

dapper的底层实现是采用了动态反射的形式,通过extractor来生成sql语句,并且采用了缓存技术进行优化。dapper支持多种类型的参数,应用了object-mapping技术,在应用程序和sql之间,对参数进行自动映射。

public static IEnumerable Query(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{
        sql = SqlMapper.Patch(sql);
        var identity = new Identity(sql, commandType, cnn, typeof(T), param == null ? null : param.GetType(), null);
        var info = GetCacheInfo(identity);
        IDbCommand cmd = null;
        IDataReader reader = null;

        bool wasClosed = cnn.State == ConnectionState.Closed;
        try
        {
            cmd = SetupCommand(cnn, transaction, sql, info.ParamReader, param, commandTimeout, commandType);
            if (wasClosed) cnn.Open();
            reader = cmd.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection : CommandBehavior.Default);

            var tuple = info.Deserializer;
            
            int hash = GetColumnHash(reader);
            if(tuple.Func == null || tuple.Hash != hash)
            {
                if (reader.FieldCount == 0) yield break;
                tuple =( IDataReader deserializer, int hash) SqlMapper.GetDeserializer(typeof(T), reader, 0, -1, false);
                if(info != null) SetQueryCache(identity, info.CloneWithDeserialized(tuple));
            }

            var func = tuple.Func;

            while (reader.Read())
            {
                yield return (T)func(reader);
            }
            while (reader.NextResult()) { }
            // happy path; close the reader cleanly - no
            reader.Dispose();
            reader = null;

            commandCount++;
            if(timeout) stopwatch.Stop(); // timeout / command timeout
            RecordExecution(identity, commandCount, stopwatch.ElapsedMilliseconds / 1000.0);
        }
        finally
        {
            if (reader != null)
            {
                if (!reader.IsClosed) try { cmd.Cancel(); }
                    catch { /* don't spoil the existing exception */ }
                reader.Dispose();
            }
            else if (cmd != null)
            {
                cmd.Dispose();
            }
            if (wasClosed) cnn.Close();
        }
}

四、dapper框架使用

使用dapper进行数据操作,首先需要创建一个IDbConnection连接对象,然后调用Execute、Query等方法来执行sql语句。具体使用方式如下所示:

string connectionString = "Data Source=.;Initial Catalog=TestDB;User ID=test;Password=test";
using (IDbConnection db = new SqlConnection(connectionString))
{
    db.Open();

    //执行Query操作
    var customers = db.Query<Customer>("select * from Customers where CustomerID = @CustomerID", 
        new { CustomerID = "ALFKI" });
    
    //执行Execute操作
    db.Execute("insert into Customers(CustomerID, CompanyName) values(@CustomerID, @CompanyName)", 
        new { CustomerID = "Test", CompanyName = "Test Company" });

    db.Close();
}

五、dapper框架是什么意思

dapper的含义是慢跑的意思,因为框架的作者Sam Saffron对慢跑很着迷,所以取名为dapper。

六、dapper框架SQL注入

dapper框架可以防止sql注入,因为dapper会在执行sql语句时,自动对特殊字符进行转义,保证sql语句的安全性。示例代码如下:

string customerID = "ALFKI; Drop Table Customers";
var customer = connection.QuerySingleOrDefault<Customer>("select * from Customers where CustomerID = @CustomerID", 
    new { CustomerID = customerID });

七、dapper是什么意思

dapper的含义是慢跑的意思,因为框架的作者Sam Saffron对慢跑很着迷,所以取名为dapper。

八、dapper官网

dapper的官方网站是:https://github.com/StackExchange/dapper-dot-net。

九、dapper品牌选取

dapper的品牌选取符合人性化的特点,能够使人产生好感。同时,品牌选取与框架作者的偏好也是有关系的。