Dapper.NET 使用简单举例
Posted 风浪子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Dapper.NET 使用简单举例相关的知识,希望对你有一定的参考价值。
概述
Dapper是.NET下一个micro的ORM,它和Entity Framework或Nhibnate不同,属于轻量级的,并且是半自动的。也就是说实体类都要自己写。它没有复杂的配置文件,一个单文件就可以了。
现在已经取代了原来的SqlHelper优点:
- 使用Dapper可以自动进行对象映射!
- 轻量级,单文件。
- 支持多数据库。
- Dapper原理通过Emit反射IDataReader的序列队列,来快速的得到和产生对象
- 由于Dapper ORM的操作实际上是对IDbConnection类的扩展,所有的方法都是该类的扩展方法。所以在使用前先实例化一个IDBConnection对象。所以调用之前,一定先加上命名空间:using Dapper;
使用举例
数据库表结构
----Book表,主表
CREATE TABLE [dbo].[Book]( [BookId] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NOT NULL, CONSTRAINT [PK_Book] PRIMARY KEY CLUSTERED ( [BookId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ----BookReview类似于book评价表 CREATE TABLE [dbo].[BookReview]( [Id] [int] IDENTITY(1,1) NOT NULL, [BookId] [int] NULL, [Content] [nvarchar](50) NULL, CONSTRAINT [PK_BookReview] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER TABLE [dbo].[BookReview] WITH CHECK ADD CONSTRAINT [FK_BookID_BookPreBookid] FOREIGN KEY([BookId]) REFERENCES [dbo].[Book] ([BookId]) GO ALTER TABLE [dbo].[BookReview] CHECK CONSTRAINT [FK_BookID_BookPreBookid] GO
实体结构
public class Book { public Book() { Reviews = new List<BookReview>(); } public int BookId { get; set; } public string Name { get; set; } public virtual List<BookReview> Reviews { get; set; } public override string ToString() { return string.Format("[{0}]------《{1}》", BookId, Name); } } //书评 public class BookReview { public int Id { get; set; } public int BookId { get; set; } public virtual string Content { get; set; } public virtual Book AssoicationWithBook { get; set; } public override string ToString() { return string.Format("{0})--[{1}]\t\"{3}\"", Id, BookId, Content); } }
-
Execute执行数据库脚本
public static void OpeartData() { string sqlconnct = System.Configuration.ConfigurationManager.ConnectionStrings["myconnect"].ConnectionString; using (IDbConnection comm = new SqlConnection(sqlconnct)) { comm.Open(); //Book book = new Book() { Name="C#9论述",Id=1 }; string query = "insert into Book(Name) values(@name)"; //添加,可以执行SQL脚本 //comm.Execute(query, book); //comm.Execute(query, new { name = "Java Learn" }); query = "UPDATE Book SET [email protected] WHERE BookId [email protected]"; //comm.Execute(query, book); //comm.Execute(query, new {name="C985426",BookId=1 }); query = "DELETE FROM Book WHERE BookId = @id"; //var idsult=comm.Execute(query, new { name = "C985426", BookId = 1 }); query = "select * from Book where [email protected]"; //var ruslt = comm.Query<Book>(query).ToList(); // var ruslt = comm.Query<Book>(query, new { BookId = 2 }).FirstOrDefault(); } }
-
Query执行数据库脚本查询
- One To More 查询
public static Book OpeartMoData() { string sqlconnct = System.Configuration.ConfigurationManager.ConnectionStrings["myconnect"].ConnectionString; using (IDbConnection conn = new SqlConnection(sqlconnct)) { conn.Open(); string query = "SELECT * FROM Book b LEFT JOIN BookReview br ON br.BookId = b.Id WHERE b.id = @id"; Book lookup = null; //Query<TFirst, TSecond, TReturn> var b = conn.Query<Book, BookReview, Book>(query, (book, bookReview) => { //扫描第一条记录,判断非空和非重复 if (lookup == null || lookup.BookId != book.BookId) lookup = book; //书对应的书评非空,加入当前书的书评List中,最后把重复的书去掉。 if (bookReview != null) lookup.Reviews.Add(bookReview); return lookup; }, new { id = 2 }, splitOn: "id").Distinct().SingleOrDefault(); return b; } }
- One To One 查询
public static BookReview OpeartData1T1() { string sqlconnct = System.Configuration.ConfigurationManager.ConnectionStrings["myconnect"].ConnectionString; using (IDbConnection conn = new SqlConnection(sqlconnct)) { BookReview br; string query = "SELECT br.Id,b.BookId,Content,Name FROM BookReview br inner JOIN Book b ON br.BookId = b.BookId WHERE br.id = @id"; using (conn) { br = conn.Query<BookReview, Book, BookReview>(query, (bookReview, book) => { bookReview.AssoicationWithBook = book; return bookReview; }, new { id = 4 }, splitOn: "BookId",commandType:CommandType.StoredProcedure).FirstOrDefault(); return br; } } }
- 执行事务
public static void BookTransaction() { string sqlconnct = System.Configuration.ConfigurationManager.ConnectionStrings["myconnect"].ConnectionString; using (IDbConnection conn = new SqlConnection(sqlconnct)) { conn.Open(); //开始事务 IDbTransaction transaction = conn.BeginTransaction(); try { string query = "DELETE FROM Book WHERE id = @id"; string query2 = "DELETE FROM BookReview WHERE BookId = @BookId"; conn.Execute(query2, new { BookId = 2 }, transaction, null, null); conn.Execute(query, new { id = 2 }, transaction, null, null); //提交事务 transaction.Commit(); } catch (Exception ex) { //出现异常,事务Rollback transaction.Rollback(); throw new Exception(ex.Message); } } }
以上是关于Dapper.NET 使用简单举例的主要内容,如果未能解决你的问题,请参考以下文章