我很难将一对多和多到多的SQL关系映射到我的pocos中的列表中。我尝试过各种方式的获取和查询以及属性,并且没有正确地映射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->分类是多对多的表,xref表ProductCategory包含ProductId和CategoryId。我得到的最接近的是用正确的对象数填充的ProductVariant列表,但是这些值是从Product映射的。
我使用PetaPoco已经很长时间了,现在正试图“升级”到NPoco V3。在使用PetaPoco时,我将使用Relator进行映射;对于NPoco,在线示例不适用于我。
发布于 2016-05-28 14:06:43
使用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);
}https://stackoverflow.com/questions/37442817
复制相似问题