美文网首页
Dapper学习

Dapper学习

作者: 尧尧i_73e9 | 来源:发表于2018-10-30 17:23 被阅读0次

    看了一些C#视频教程,在ORM框架下被推荐使用Dapper,下面记录一下操作的步骤:

    https://blog.csdn.net/qq_35309370/article/details/80927435

    1.Nuget安装

    Dapper 1.50.5需要在.Net Framework 4.5.1及以上版本进行安装

    2.连接操作:前提——创建好数据库

    配置文件中:

    <connectionStrings>

        <add name="dapper" connectionString="Data Source=localhost;Initial Catalog=DapperDemoDb;Integrated Security=true;"/>

      </connectionStrings>

    C#程序中:

    public static string ConnectedString

    {

    get { return ConfigurationManager.ConnectionStrings["dapper"].ConnectionString; }

    }

    IDbConnection conn = new SqlConnection(ConnectedString)

    3.CRUD

    3.1 插入

    单行插入:

    Book book = new Book(){  Name = "c#本质论"};

    string query = "insert into BookTbl(Name) values(@name)";

    int res=conn.Execute(query, book);

    批量插入:

    var books = Enumerable.Range(0, 10).Select(i => { return new Book() {Name = "图书" + i}; });

    string query = "insert into booktbl values(@name)";

    int res=conn.Execute(query, books);

    注意:

    (1)values括号包含的项数>=实体实例化中赋值的量的个数,如,entity中有5个属性,赋值3个,则values中至少应包含赋值的3个属性的属性名;(2)数据库表中字段名与实体类属性对应;

    3.2 更新

    string query = "UPDATE Book SET Name=@name WHERE id =@id";

    conn.Execute(query, book);

    3.3 删除

    string query = "DELETE FROM Book WHERE id = @id";

    conn.Execute(query, book);

    conn.Execute(query, new { id = id });

    3.1-3.3小结

    CUD操作与sql语句基本一致,不同的是在执行时,输入强类型的参数,方法自动将实例中的属性与操作语句中的属性进行对应。

    3.4 查询

    1-n查询:查询book和对应的所有书评;当使用where条件指定book的id时,可以得到单个book查询,以及对应的bookreview列表;可以控制是否进行列表查询

    //查询图书时,同时查找对应的书评,并存在List中。实现1--n的查询操作

    string query = "SELECT * FROM Booktbl b LEFT JOIN Bookviewtbl br ON br.BookId = b.Id ";

    Book lookup = null;

    //Query<TFirst, TSecond, TReturn>

    var b = conn.Query<Book, BookReview, Book>(query,(book, bookReview) =>{

    //扫描第一条记录,判断非空和非重复

    if (lookup == null || lookup.Id != book.Id)

    lookup = book;

    //书对应的书评非空,加入当前书的书评List中,最后把重复的书去掉。

    if (bookReview != null)

    lookup.Reviews.Add(bookReview);

    return lookup;

    }).Distinct();

    4. 事务

    using (conn)

    {

    //开始事务

    IDbTransaction transaction = conn.BeginTransaction();

      try

      {

        string query = "DELETE FROM Booktbl WHERE id = @id";

        string query2 = "DELETE FROM BookReview WHERE BookId = @BookId";

        conn.Execute(query2, new { BookId = id }, transaction, null, null);

        conn.Execute(query, new { id = id }, transaction, null, null);

        //提交事务

        transaction.Commit();

      }

      catch (Exception ex)

      {

        //出现异常,事务Rollback

        transaction.Rollback();

        throw new Exception(ex.Message);

      }

    }

    相关文章

      网友评论

          本文标题:Dapper学习

          本文链接:https://www.haomeiwen.com/subject/zfibtqtx.html