zoukankan      html  css  js  c++  java
  • 轻量级ORM框架Dapper应用五:使用Dapper实现Join操作

    在这篇文章中,讲解如何使用Dapper使用Inner join的操作

    1、新创建两张表:Users表和Product表

    Users表定义如下:

    CREATE TABLE [dbo].[Users](
        [UserId] [int] IDENTITY(1,1) NOT NULL,
        [UserName] [varchar](16) NULL,
        [Email] [varchar](32) NULL,
        [Address] [varchar](128) NULL,
    PRIMARY KEY CLUSTERED 
    (
        [UserId] 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

     Product表定义如下:

    CREATE TABLE [dbo].[Product](
        [ProductId] [int] IDENTITY(1,1) NOT NULL,
        [ProductName] [varchar](16) NULL,
        [Price] [decimal](8, 2) NULL,
        [UserId] [int] NULL,
    PRIMARY KEY CLUSTERED 
    (
        [ProductId] 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

     查看Users表和Product表会发现两张表通过UserId外键关联起来,然后我们需要在Product实体类上面进行修改,添加一个User的实体属性,修改后的代码如下:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace DapperApplicationJoin.Model
     8 {
     9     public class Product
    10     {
    11         public int ProductId { get; set; }
    12 
    13         public string ProductName { get; set; }
    14 
    15         public User UserOwner { get; set; }
    16 
    17         public string Price { get; set; }
    18     }
    19 }

     User实体类定义如下:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace DapperApplicationJoin.Model
     8 {
     9     public class User
    10     {
    11         public int UserId { get; set; }
    12 
    13         public string UserName { get; set; }
    14 
    15         public string Email { get; set; }
    16 
    17         public string Address { get; set; }
    18     }
    19 }

     2、Main方法定义如下

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.Configuration;
     7 using System.Data;
     8 using System.Data.SqlClient;
     9 using Dapper;
    10 using DapperApplicationJoin.Model;
    11 
    12 namespace DapperApplicationJoin
    13 {
    14     class Program
    15     {
    16         static void Main(string[] args)
    17         {
    18             string conn = ConfigurationManager.ConnectionStrings["AppConnection"].ConnectionString;
    19             using (IDbConnection connection = new SqlConnection(conn))
    20             {
    21                 string sql = @"
    22                             select p.ProductName,p.Price,u.UserName,u.UserId,u.Email,u.Address
    23                             from Product as p
    24                             join Users as u
    25                             on p.UserId=u.UserId;
    26                             ";
    27 
    28                 var result = connection.Query<Product, User, Product>(sql,
    29                                        (product, users) =>
    30                                        {
    31                                            product.UserOwner = users; return product;
    32                                        }, splitOn: "UserName");
    33                 var query = connection.Query(sql);
    34                 // 输出 使用动态类型
    35                 query.AsList().ForEach(p => 
    36                 {
    37                     Console.WriteLine("产品名称:" + p.ProductName + ",产品价格:" + p.Price + ",用户姓名:" + p.UserName);
    38                 });
    39             }
    40 
    41             Console.ReadKey();
    42         }
    43     }
    44 }

     splitOn参数的含义:代码中的splitOn是UserName,运行时,会从查询结果所有字段列表的最后一个字段开始进行匹配,一直到找到UserName这个字段(大小写忽略无所谓),找到的第一个UserName字段匹配的Product类的UserName属性,那么从UserName到最后一个字段都属于Product,UserName以前的字段都被影射到Users,通过 (T, P) => {return T; },把两个类的实例解析出来。就实现了两个数据的解析,要不然dapper也不知道哪个是Product哪个是Users的属性。

    除了可以使用上面的方法以外,还可以使用直接查询SQL语句的方式:

    using (IDbConnection connection = new SqlConnection(conn))
    {
                    string sql = @"
                                            select p.ProductName,p.Price,u.UserName,u.UserId,u.Email,u.Address
                                            from Product as p
                                            join Users as u
                                            on p.UserId=u.UserId;
                                            ";
                    var query = connection.Query(sql);
                    // 输出 使用动态类型
                    query.AsList().ForEach(p =>
                    {
                        Console.WriteLine("产品名称:" + p.ProductName + ",产品价格:" + p.Price + ",用户姓名:" + p.UserName);
                    });
    } 

     运行结果如下:

    示例代码下载地址:https://pan.baidu.com/s/1gfwA9d5

  • 相关阅读:
    HDU 5492 Find a path
    codeforce gym 100548H The Problem to Make You Happy
    Topcoder SRM 144 Lottery
    codeforce 165E Compatible Numbers
    codeforce gym 100307H Hack Protection
    区间DP总结
    UESTC 1321 柱爷的恋爱 (区间DP)
    HDU 4283 You Are the One (区间DP)
    HDU 2476 String painter (区间DP)
    UESTC 426 Food Delivery (区间DP)
  • 原文地址:https://www.cnblogs.com/dotnet261010/p/8168865.html
Copyright © 2011-2022 走看看