Home > OS >  Null exception while working with joining tables in ASP.NET MVC
Null exception while working with joining tables in ASP.NET MVC

Time:01-30

I have product, Productsize and Size entities.

Productsize entity contains ProductID and SizeID which are foreign key of Product and Size entity. I am adding size filter in shop page. List of size ids are coming from view .I am checking if the size ids are there in Productsize entity and displaying that product only. In if condition it is showing null exception

List<int> sizeIDs = !string.IsNullOrEmpty(SizeIds) ? SizeIds.Split(',').Select(x => int.Parse(x)).ToList() : new List<int>();

var products = db.Products.ToList();

if (sizeIDs.Any())
{
    products = products.Where(x=>sizeIDs.Contains(x.ProductSizes.FirstOrDefault()
                                          .SizeID)).ToList();
}    

CodePudding user response:

try:

List<int> sizeIDs = !string.IsNullOrEmpty(SizeIds) ? SizeIds.Split(',').Select(x => int.Parse(x)).ToList() : new List<int>();

var products = db.Products.ToList();

if (sizeIDs.Any())
{
    products = products.Where(x=>sizeIDs.Contains(x.ProductSizes.FirstOrDefault()?
                                          .SizeID)).ToList();
}    

.FirstOrDefault()?.SizeID

or :

List<int> sizeIDs = !string.IsNullOrEmpty(SizeIds) ? SizeIds.Split(',').Select(x => int.Parse(x)).ToList() : new List<int>();

var products = db.Products.ToList();

if (sizeIDs.Any())
{
    products = products.Where(x=>x.ProductSizes.Any() && sizeIDs.Contains(x.ProductSizes.First().SizeID)).ToList();
} 

Update: lets try this query:

List<int> sizeIDs = !string.IsNullOrEmpty(SizeIds) ? SizeIds.Split(',').Select(x => int.Parse(x)).ToList() : new List<int>();

            var products = db.Products.ToList();

            if (sizeIDs.Any())
            {
                products = products.Where(x => x.ProductSizes.Any(s=> sizeIDs.Contains(s.SizeID)) ).ToList();
            }   
  •  Tags:  
  • Related