【发布时间】:2021-04-28 13:42:56
【问题描述】:
我有两个表(简化视图):
产品
产品 ID (PK)
名称
可变乘积(位)
产品变化
ProductVariationId (PK)
名称
产品 ID (FK)
产品图片
ProductImageId (PK)
图片网址
产品 ID (FK)
ProductVariationId (FK) NULLABLE
我需要连接这两个表以输出“ProductSearch”列表,这是一个简化的视图模型。
一个产品可以有一个主图像,一个变体可以有它自己的变体图像。
在连接中,如果变体图像值为空,我想为变量产品指定父图像。
我的代码如下:
//Single products first
var products = await _context.Product.Where(p => p.Enabled == true && p.VariableProduct == false)
.Include(e => e.ProductImages.Where(p => p.IsDefault == true && p.ProductVariationId == null))
.Select(p => new ProductSearch()
{
ProductId = p.ProductId,
ProductVariationId = null,
Name = p.Name,
ImageUrl = p.ImageUrl.FirstOrDefault().ImageUrl
}).ToListAsync();
//Variables
var productVariables = await _context.ProductVariation
.Include(p => p.Product).
.Include(e => e.ProductImages.Where(p.ProductVariationId == e.ProductVariationId))
.Select(p => new ProductSearch()
{
ProductId = p.ProductId,
ProductVariationId = p.ProductVariationId,
Name = p.Product.Name + " (" + p.Name + ")",
ImageUrl = p.ProductImages.Any() ? p.ProductImages.First().ImageUrl : "PARENT IMAGE NEEDED HERE"
}).ToListAsync();
var productSearch = products.Union(productVariables).OrderBy(p => p.Name).ToList();
return productSearch;
此代码运行良好并按预期生成我的列表,除了字符串“此处需要父图像”之外。
我之前确实问过一个类似的问题(得到了回答),但那是创建一个产品列表,包括它们的变量(如果有的话),而这个列表的不同之处在于它不包括任何类型的任何集合.
非常感谢,像往常一样。
【问题讨论】:
-
你忘了这里的 lambda 左边吗:
.Include(e => e.ProductImages.Where(p.ProductVariationId == e.ProductVariationId))?应该是p=> -
你能发布你的课程吗?查询完全错误,我无法对您的模型进行逆向工程。
标签: c# entity-framework linq