首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NPoco一对多和多对多

NPoco一对多和多对多
EN

Stack Overflow用户
提问于 2016-05-25 16:23:14
回答 1查看 2.3K关注 0票数 0

我很难将一对多和多到多的SQL关系映射到我的pocos中的列表中。我尝试过各种方式的获取和查询以及属性,并且没有正确地映射pocos。下面是类和SQL的简化版本:

波科斯:

代码语言:javascript
复制
[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查询:

代码语言:javascript
复制
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,在线示例不适用于我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-28 14:06:43

使用NPoco 3,您只能映射1到多或多对多的关系.

要使示例工作,必须存在的项是Product中的NPoco.PrimaryKey("ProductId")标记。

所以你这么做:

代码语言:javascript
复制
string sql = "sql with product-categorie relation";
List<Product> products = db.Fetch<Product>(x => x.Categories, sql);

代码语言:javascript
复制
string sql = "sql with product-productVariant relation";
List<Product> products = db.Fetch<Product>(x => x.ProductVariants, sql);

这将为您提供带有类别列表或ProductVariants列表的产品列表,但不是两者兼备。

您可以使用第一种方法,获取包含类别的产品列表,然后:

代码语言:javascript
复制
foreach(Product aProduct in products) 
{
    string productVariantSQL = "SQL to retrieve productVariant for current product";
    aProduct.ProductVariants = db.Fetch<ProductVariant>(productVariantSQL);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37442817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档