NPoco One-To-Many和Many-To-Many

时间:2016-05-25 16:23:14

标签: npoco

我很难将一对多和多对多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-&gt; ProductVariant是一对多的,ProductVariant表携带ProductId;和Product-&gt;类别是多对多的,带有带有ProductId和CategoryId的外部参照表[ProductCategory]。我最接近的是ProductVariant列表,其中填充了正确数量的对象,但这些值是从Product数据映射的。

我和PetaPoco合作了很长时间,现在正试图升级&#34;到NPoco V3。与PetaPoco一起,我会使用Relators进行映射;与NPoco一起,网上的例子不适合我。

1 个答案:

答案 0 :(得分:0)

使用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);
}