I've trying to make a conditional select using EF Core, but i think i'm a litle bit confusing about how to do this. I have two tables in my MySql Schema: Products
and Offers
. I want to select all products and merge with the offers, overriding the product with your current promotional value. I've try to use include
, join
and all sort of things, but i think the problem is my logic. Here is my current EF core select, without 'merge' with the offers.
List<ProductViewModel> viewModel = await _context.product
.Where(p => p.establishment_id == EstablishmentId)
.Select(p => new ProductViewModel()
{
Id = p.id,
Name = p.name,
Description = p.description,
Rating = p.rating,
Price = p.price,
Photos = p.product_photo
.Where(pho => pho.product_id == p.id)
.Select(pho => new ProductPhotoViewModel()
{
Path = pho.path
}).ToList(),
Category = _context.category
.Join(_context.product_has_category, c => c.id, phc => phc.category_id, (c, phc) => new {c, phc})
.Where(c => c.phc.product_id == p.id)
.Select(c => new CategoryViewModel()
{
Id = c.phc.category.id,
Name = c.phc.category.name
}).SingleOrDefault()
}).ToListAsync();
All help are useful! Many thanks!
Use the ternary conditional operator ?:
along with a not equals condition !=
to add a conditional to your select statement.
.Select(p => new ProductViewModel()
{
Id = p.id,
Name = p.name,
Description = p.description,
Rating = p.rating,
Price = p.offer != null ? p.offer.sale_price : p.price
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.