标签:
Dapper是一款轻量级ORM工具(Github)。如果你在小的项目中,使用Entity Framework、NHibernate 来处理大数据访问及关系映射,未免有点杀鸡用牛刀。你又觉得ORM省时省力,这时Dapper 将是你不二的选择。
CREATE TABLE [dbo].[CICUser] ( [UserId] [int] IDENTITY(1, 1) PRIMARY KEY NOT NULL, [Username] [nvarchar](256) NOT NULL, [PasswordHash] [nvarchar](500) NULL, [Email] [nvarchar](256) NULL, [PhoneNumber] [nvarchar](30) NULL, [IsFirstTimeLogin] [bit] DEFAULT(1) NOT NULL, [AccessFailedCount] [int] DEFAULT(0) NOT NULL, [CreationDate] [datetime] DEFAULT(GETDATE()) NOT NULL, [IsActive] [bit] DEFAULT(1) NOT NULL ) CREATE TABLE [dbo].[CICRole] ( [RoleId] [int] IDENTITY(1, 1) PRIMARY KEY NOT NULL, [RoleName] [nvarchar](256) NOT NULL, ) CREATE TABLE [dbo].[CICUserRole] ( [Id] [int] IDENTITY(1, 1) PRIMARY KEY NOT NULL, [UserId] [int] FOREIGN KEY REFERENCES [dbo].[CICUser] ([UserId]) NOT NULL, [RoleId] [int] FOREIGN KEY REFERENCES [dbo].[CICRole] ([RoleId]) NOT NULL )
在创建实体类时,属性名称一定要与数据库字段一一对应。
public class User { public User() { Role = new List<Role>(); } public int UserId { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } public bool IsFirstTimeLogin { get; set; } public int AccessFailedCount { get; set; } public DateTime CreationDate { get; set; } public bool IsActive { get; set; } public List<Role> Role { get; set; } } public class Role { public int RoleId { get; set; } public string RoleName { get; set; } } public class Customer { public int UserId { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } public bool IsFirstTimeLogin { get; set; } public int AccessFailedCount { get; set; } public DateTime CreationDate { get; set; } public bool IsActive { get; set; } public Role Role { get; set; } }
实体类
private static void OneToOne(string sqlConnectionString) { List<Customer> userList = new List<Customer>(); using (IDbConnection conn = GetSqlConnection(sqlConnectionString)) { string sqlCommandText = @"SELECT c.UserId,c.Username AS UserName, c.PasswordHash AS [Password],c.Email,c.PhoneNumber,c.IsFirstTimeLogin,c.AccessFailedCount, c.CreationDate,c.IsActive,r.RoleId,r.RoleName FROM dbo.CICUser c WITH(NOLOCK) INNER JOIN CICUserRole cr ON cr.UserId = c.UserId INNER JOIN CICRole r ON r.RoleId = cr.RoleId"; userList = conn.Query<Customer, Role, Customer>(sqlCommandText, (user, role) => { user.Role = role; return user; }, null, null, true, "RoleId", null, null).ToList(); } if (userList.Count > 0) { userList.ForEach((item) => Console.WriteLine("UserName:" + item.UserName + "----Password:" + item.Password + "-----Role:" + item.Role.RoleName + "\n")); Console.ReadLine(); } }
public static void InsertObject(string sqlConnectionString) { string sqlCommandText = @"INSERT INTO CICUser(Username,PasswordHash,Email,PhoneNumber)VALUES( @UserName, @Password, @Email, @PhoneNumber )"; using (IDbConnection conn = GetSqlConnection(sqlConnectionString)) { User user = new User(); user.UserName = "Dapper"; user.Password = "654321"; user.Email = "Dapper@infosys.com"; user.PhoneNumber = "13795666243"; int result = conn.Execute(sqlCommandText, user); if (result > 0) { Console.WriteLine("Data have already inserted into DB!"); } else { Console.WriteLine("Insert Failed!"); } Console.ReadLine(); } }
/// <summary> /// Execute StoredProcedure and map result to POCO /// </summary> /// <param name="sqlConnnectionString"></param> public static void ExecuteStoredProcedure(string sqlConnnectionString) { List<User> users = new List<User>(); using (IDbConnection cnn = GetSqlConnection(sqlConnnectionString)) { users = cnn.Query<User>("dbo.p_getUsers", new { UserId = 2 }, null, true, null, CommandType.StoredProcedure).ToList(); } if (users.Count > 0) { users.ForEach((user) => Console.WriteLine(user.UserName + "\n")); } Console.ReadLine(); } /// <summary> /// Execute StroedProcedure and get result from return value /// </summary> /// <param name="sqlConnnectionString"></param> public static void ExecuteStoredProcedureWithParms(string sqlConnnectionString) { DynamicParameters p = new DynamicParameters(); p.Add("@UserName", "cooper"); p.Add("@Password", "123456"); p.Add("@LoginActionType", null, DbType.Int32, ParameterDirection.ReturnValue); using (IDbConnection cnn = GetSqlConnection(sqlConnnectionString)) { cnn.Execute("dbo.p_validateUser", p, null, null, CommandType.StoredProcedure); int result = p.Get<int>("@LoginActionType"); Console.WriteLine(result); } Console.ReadLine(); } 使用示例代码 string connString=ConfigurationManager.ConnectionStrings["mall"].ConnectionString; //执行查询 using (MySqlConnection conn = new MySqlConnection(connString)) { var books = conn.Query<Book>("select Title,Author from Book where Author=@Author", new { Author = "Ben" }); foreach (var item in books) { Console.WriteLine(item.Title + item.Author); } Console.ReadKey(); } //执行存储过程(带参) using (MySqlConnection conn = new MySqlConnection(connString)) { var books = conn.Query<Book>("Prc_book", new { Auth = "Ben" }, null, true, null, CommandType.StoredProcedure); foreach (var item in books) { Console.WriteLine(item.Title + item.Author); } Console.ReadKey(); } //执行连接查询 using (MySqlConnection conn = new MySqlConnection(connString)) { var results = conn.Query(@"SELECT*FROM book AS a INNER JOIN category AS b ON a.Id=b.Id"); foreach (var item in results) { Console.WriteLine(item.Title + item.Author); } Console.ReadKey(); } //插入单行数据 using (MySqlConnection conn = new MySqlConnection(connString)) { var results = conn.Execute(@"INSERT INTO category VALUES(null,@name,@parentid)", new Category { Name = @"数据", ParentId = 003 }); Console.WriteLine(results); Console.ReadKey(); } //插入多行数据 var list = new List<Category>(); for (int i = 0; i < 200; i++) { list.Add(new Category { Name = @"Shopping", ParentId = 003 }); } using (MySqlConnection conn = new MySqlConnection(connString)) { var results = conn.Execute(@"INSERT INTO category VALUES(null,@name,@parentid)", list); Console.WriteLine(results); Console.ReadKey(); } //多个查询 using (MySqlConnection conn = new MySqlConnection(connString)) { var results = conn.QueryMultiple(@"select*from book where Author=@Author;select*from category where Name=@Name", new{Author="Ben",Name="JAVA"}); var books=results.Read<Book>(); foreach (var item in books) { Console.WriteLine(item.Title); } var category = results.Read<Category>(); foreach (var item in category) { Console.WriteLine(item.Id); } Console.ReadKey(); }
标签:
原文地址:http://www.cnblogs.com/sherlockholmes/p/5287053.html