0

我在 Sql Server 中有 3 个表,一对一的关系。

关键是所有 3 个表中的索引。

3个实体:

public class Client
{
     public int Indice { get; set; }
     public string Name { get; set; }
     public string Surname { get; set; }
     public string Company { get; set; }
     public string Tel1 { get; set; }
     public string Tel2 { get; set; }
}

public class CallClient
{
     public int Indice { get; set; }
     public string CallDateTime { get; set; }
     public string Status { get; set; }
}

public class ResponsePollClient
{
     public int Indice { get; set; }
     public string Question1 { get; set; }
     public string Question2 { get; set; }
     public string Question3 { get; set; }
     public string StatusPoll { get; set; }
}

我有这个主要实体

public class DataClient
{
     public Client client { get; set; }
     public CallClient callClient { get; set; }
     public ResponsePollClient pollClient { get; set; }
}

SQL:

选择 c.Indice, .... , cc.Indice, ... , pc.Indice, ...
from Client c
inner join CallClient cc on c.Indice = cc.Indice
inner join PollClient pc on c.Indice = pc .指数

如何使用 Dapper 填充列表实体?

4

2 回答 2

1

以下代码应映射您的 pocos:

   var sql = @"SELECT c.Indice 
             , c.Name
             , ....
             , cc.Indice
             , cc.CallDateTime 
             , ....
             , rpc.Indice 
             , rpc.Question1 
             , .... 
        FROM Client c
  INNER JOIN CallClient cc on c.Indice = cc.Indice
  INNER JOIN PollClient pc on c.Indice = pc.Indice";

        using (var conn = new SqlConnection())
        {
            var res = conn.Query<Client, CallClient, ResponsePollClient, DataClient>(sql, (c, cc, pc) =>
            {
                   var d = new DataClient() 
                   {
                     client = c, 
                     callClient = cc, 
                     pollClient = pc
                    };

                return dc;
            }, splitOn: "Indice");
        }
于 2020-04-23T09:59:08.697 回答
1

代码应如下所示:

var entityList = connection.Query<DataClient, Client, CallClient,ResponsePollClient,DataClient>(
            sql,
            (dataClient, client, callClient, responsePollClient) =>
            {
                dataClient.client = client;
                dataClient.callClient = callClient;
                dataClient.pollClient = responsePollClient;
                return dataClient;
            },
            splitOn: "Indice").ToList();

这非常简单,您可以在此处找到完整的文档

于 2020-04-23T10:04:47.963 回答