how to add where condition in include table in linq

Viewed 34

I can use the dynamic model I want to add where condition in the "Tbl_ProductImg" table in this table I want only those record which has "isActive" value 1.

model.Product = db.Tbl_Product
  .Include(t => t.Tbl_Product_Category)
  .Include(y=>y.Tbl_Product_Dimensions)
  .Include(I => I.Tbl_ProductImg)
  .Where(x => x.Id == id && x.IsActive == 1 && x.Tbl_ProductImg.Any(y=>y.isActive==1))
  .FirstOrDefault();

var result = Global.jsonConvert(model);
1 Answers

I assume that you have a Product class and ProductImg class which represents your database tables and if you want to get your all ProductImg data.

Product.cs:

public class Product
{
    public int Id { get; set; }
    public int IsActive { get; set; }

    public IEnumerable<ProductCategory> ProductCategories { get; set; }
    public IEnumerable<ProductDimension> ProductDimensions { get; set; }
    public IEnumerable<ProductImg> ProductImages { get; set; }
}

ProductImg.cs:

public class ProductImg
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int IsActive { get; set; }

    public Product Product { get; set; }
}

And you can get your Active Product Images with:

model.Product = db.Tbl_Product
                .Where(p => p.Id == id && p.IsActive == 1)
                .Select(p => new Product
                {
                    Id = p.Id,
                    IsActive = p.IsActive,
                    //and you can get whatever you want..
                    ProductImages = p.ProductImages.Where(pi => pi.ProductId == p.Id && pi.IsActive == 1).Select(pi => new ProductImg
                    {
                        Id = pi.Id,
                        IsActive = pi.IsActive
                        //and you can get whatever you want..
                    })
                }).FirstOrDefault();
Related