简体   繁体   English

EF Core的条件选择

[英]Conditional select with EF Core

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. 我正在尝试使用EF Core进行条件选择,但我认为我对如何执行此操作感到有些困惑。 I have two tables in my MySql Schema: Products and Offers . 我的MySql模式中有两个表: ProductsOffers 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. 我尝试使用includejoin和各种各样的东西,但是我认为问题是我的逻辑。 Here is my current EF core select, without 'merge' with the offers. 这是我当前的EF核心选择,没有与报价“合并”。

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语句中。

.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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM