【问题标题】:NPoco One-To-Many and Many-To-ManyNPoco 一对多和多对多
【发布时间】:2016-05-25 16:23:14
【问题描述】:

我在将一对多和多对多 SQL 关系映射到我的 pocos 中的列表时遇到了困难。我已经尝试了所有方式的 Fetch 和 Query 以及属性,但我没有正确映射 pocos。这是类和 SQL 的简化版本:

波科斯:

[NPoco.TableName("Product")]
[NPoco.PrimaryKey("ProductId")]
public class Product
{
    public int ProductId { get; set; }
    public List<Category> Categories { get; set; }
    public string Name { get; set; }
    public List<ProductVariant> ProductVariants { get; set; }
}

[NPoco.TableName("Category")]
[NPoco.PrimaryKey("CategoryId")]
public class Category : ModifiedDomainObject
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
}

[NPoco.TableName("ProductVariant")]
[NPoco.PrimaryKey("ProductVariantId")]
public class ProductVariant : ModifiedDomainObject
{
    public int ProductVariantId { get; set; }
    public string Name { get; set; }
}

SQL 查询:

SELECT[Product].[ProductId], 
[Product].[PublicId], 
[Product].[Name], 
[Category].[CategoryId],
[Category].[Name],
[ProductVariant]
[ProductVariantId],
[ProductVariant].[ProductId],
[ProductVariant].[Name],
FROM[Product]
JOIN[ProductCategory] on[ProductCategory].[ProductId] = [ProductCategory].[ProductId]
JOIN[Category] ON[ProductCategory].[CategoryId] = [Category].[CategoryId]
LEFT OUTER JOIN[ProductVariant] ON[Product].[ProductId] = [ProductVariant].[ProductId]
WHERE[Product].[ProductId] = 1 
ORDER BY[Product].[ProductId], 
[Category].[CategoryId], 
[ProductVariant].[ProductVariantId];

所以,Product->ProductVariant 是一对多的,其中 ProductVariant 表携带 ProductId; Product->Category 是多对多的,带有一个带有 ProductId 和 CategoryId 的外部参照表 [ProductCategory]。我得到的最接近的是 ProductVariant 列表,其中填充了正确数量的对象,但这些值是从 Product 数据映射的。

我与 PetaPoco 合作了很长时间,现在正尝试“升级”到 NPoco V3。如果使用 PetaPoco,我会使用 Relators 进行映射;使用 NPoco,在线示例对我不起作用。

【问题讨论】:

    标签: npoco


    【解决方案1】:

    使用 NPoco 3,您只能映射 1 个一对多或多对多关系。

    示例必须存在才能工作的项目是 Product 类中的 [NPoco.PrimaryKey("ProductId")] 标记。

    所以你这样做:

    string sql = "sql with product-categorie relation";
    List<Product> products = db.Fetch<Product>(x => x.Categories, sql);
    

    或

    string sql = "sql with product-productVariant relation";
    List<Product> products = db.Fetch<Product>(x => x.ProductVariants, sql);
    

    这将为您提供带有类别列表或 ProductVariants 列表的产品列表,但不能同时获得两者。

    您可以使用第一个,获取带有类别的产品列表,然后:

    foreach(Product aProduct in products) 
    {
        string productVariantSQL = "SQL to retrieve productVariant for current product";
        aProduct.ProductVariants = db.Fetch<ProductVariant>(productVariantSQL);
    }
    

    【讨论】:

    • 感谢您的回答,我相信这是正确的。唯一的解决方案导致 N+1 行为(100 个产品 = 101 个 SQL 查询),这似乎是我一直在使用的 PetaPoco 的倒退。
    猜你喜欢
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 2020-07-12
    • 2011-09-07
    • 2015-07-05
    • 2012-11-11
    相关资源
    最近更新 更多