简体   繁体   English

创建多个连接查询 - Dapper

[英]Create Multiple join query - Dapper

recently i'm working on an application and my instructor asked me to use Dapper as ORM.最近我正在开发一个应用程序,我的导师让我使用 Dapper 作为 ORM。 This is the first time to work on it.这是第一次工作。 I want to create a join query for 3 tables and store the value in custom object.我想为 3 个表创建一个连接查询并将值存储在自定义 object 中。

Here are the tables:以下是表格:

public class Customer
{
public int id { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public List<Orders> Order { get; set; }
}


public class Orders
{
public int id { get; set; }
public string code{ get; set; }
public string name { get; set; }
public  Customer Customer { get; set; }
public  Product Product  { get; set; }
}



public class Product
{
public int id { get; set; }
public string name { get; set; }
public string price { get; set; }
public  List<Orders> Order { get; set; }
}

This DTO Class:此 DTO Class:

public class CustomDTO
{
public string CustomerName { get; set; }
public string OrderName { get; set; }
public string ProductName { get; set; }
}

I want to store result executed from the dapper join query into CustomDTO我想将从 dapper join 查询执行的结果存储到 CustomDTO

As has been pointed out, you really need to supply more info in your post so people don't have to assume too much.正如已经指出的那样,您确实需要在您的帖子中提供更多信息,这样人们就不必假设太多。 From what you've said, one possible approach is this:根据您所说,一种可能的方法是:

using (var connection = new SqlConnection("YOUR_CONNECTION_STRING"))
{
    connection.Open();

    string cmdTxt = @"SELECT o.name, c.name, p.name
        FROM Orders o
        INNER JOIN Customers c ON o.customerId = c.Id 
        INNER JOIN Products p ON o.productId = p.Id;";

    var results = await connection.QueryAsync<CustomDTO>(cmdTxt);

    if(results.Any()) {
        //do something with the list of `CustomDTO`
    }

    connection.Close();
}

Note: I'm assuming your Orders table has the relevant foreign keys.注意:我假设您的 Orders 表具有相关的外键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM