将查询结果映射到类(子类)

问题描述 投票:0回答:1

C#中查询结果到对象映射的问题

前端期望后端 JSON 是这样的:

unBookedOrders: [{
    orderId: 865470,
    orderCollectionNumber: 6114353,
    orderAddress: {
        address: 'Gamlestadsvägen 123',
        city: 'Göteborg'
    },
    customer: {
        firmName: 'Firm Name',
        agentName: 'Agent Name'
    },
},
...
]

为此目的,在后端我有以下课程:

public class Order
{
    public int orderId { get; set; }
    public int orderCollectionNumber { get; set; }
    public OrderAddress orderAddress { get; set; }
    public Customer customer { get; set; }
}
public class OrderAddress
{
    public string address { get; set; }
    public string city { get; set; }
}
public class Customer
{
    public string firmName { get; set; }
    public string agentName { get; set; }
}

所有这些数据来自查询:

var orders = await _session.QueryAsync<Orders>(@"
    SELECT
        o.Id AS OrderId,
        oc.OrderCollectionNumber,
        bo.AddressLine1 AS Address,
        bo.AddressCity AS City,
        c.FirstName,
        c.AgentName
from Table1 opp ...
WHERE ...

它很好地映射到 orderId 和 orderCollectionNumber。

问题:如何将OrderAddress和Customer映射到查询结果?

c# sql dapper
1个回答
1
投票

您可以使用 Dapper 来完成这项工作(例如有产品和类别而不是订单和地址):

using(var connection = new SqlConnection(connectionString))
{
    var sql = @"SELECT ProductID, ProductName, p.CategoryID, CategoryName
                FROM Products p 
                INNER JOIN Categories c ON p.CategoryID = c.CategoryID";
                
    var products = await connection.QueryAsync<Product, Category, Product>(sql, (product, category) => {
        product.Category = category;
        return product;
    }, 
    splitOn: "CategoryId" );
    
    products.ToList().ForEach(product => Console.WriteLine($"Product: {product.ProductName}, Category: {product.Category.CategoryName}"));
    
    Console.ReadLine();
}

有关详细信息,请参阅:https://www.learndapper.com/relationships

© www.soinside.com 2019 - 2024. All rights reserved.