精巧的嵌套对象 [英] Dapper nested objects

查看:59
本文介绍了精巧的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经关注了

我期望的是2个订单的列表,其中每个订单包含2个产品

解决方案

您有多个具有相同名称的列.Dapper将如何知道该拆分哪一个?它只会选择第一个

在任何情况下, SELECT * 通常都是不好的,因为您可能获取的信息远远超出了需要.

您需要做的是重写查询以使其具有不同的列名,并且仅询问对象中实际需要的信息.


您还需要在这里保证订购,以便将子项分组在一起.像这样的东西:
ORDER BY订单ID,客户ID ``

I am following this already existing question to make it work for a similar case in my scenario but there is something missing and I hope you can help me.

My class structure:

class Order
{
    public int Order_Id { get; set; }
    public Customer Customer { get; set; }
    public List<Product> Products { get; set; }

    public static string query = @"SELECT ORD.* , CUST.*, PROD.* FROM [Order] AS ORD
                                    JOIN dbo.Customer AS CUST ON ORD.Customer_Id = CUST.Customer_Id
                                    JOIN dbo.Product AS PROD ON PROD.Product_Id = ORD.Product_Id";
}

class Customer
{
    public int Customer_Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

class Product
{
    public int Product_Id { get; set; }
    public string Product_Name { get; set; }
}

My dapper call:

var result = connection.Query<Order, Customer, Product, Order>(Order.query,
(order, customer, products) => {
    order.Customer = customer;
    order.Products = new List<Product>();
    order.Products.Add(products);
    return order;
}, splitOn: "Customer_Id, Product_Id").AsQueryable();

The customer gets filled correctly but not the list of products. This is what is in the DB:

What I would expect is a list of 2 orders, where each one contains 2 products

解决方案

You have multiple columns with the same name. How will Dapper know which one to split on? It is just going to pick the first

In any case, SELECT * is generally bad, as you may be pulling far more info than you need.

What you need to do is rewrite your query to have distinct column names, and only ask for info that you actually need in your objects.


You also need guaranteed ordering here, so that child items are grouped together. Something like:
ORDER BY Order_id, Customer_Id ``

这篇关于精巧的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆