Linq join list and table

c# entity-framework-core linq

Question

I have a List<string> of ProductTypes such as Vegetables, Dairy, Meat which I receive from a query string in Asp.Net Core.

In the database, there is a Product table which contains a ProductType column that has each product's type in a text field)

I want to select from the Product database table all the Products that are in the ProductTypes list as received. I did this:

var Result =  (from p in _context.Product
             join t in ProductTypes on p.ProductType equals t  select p).ToList();

My effort above has an (incorrect) empty result except if only one ProductType is passed, in which case it works correctly.

How can I accomplish a correct Result set if multiple ProductTypes are passed?

1
0
12/4/2017 6:04:00 AM

Accepted Answer

You can use Contains instead of a join:

var result =
    from p in _context.Product
    where ProductTypes.Contains(p.ProductType)
    select p;

You rarely need joins in LINQ and in your special case where you have an in memory list and a database table, Contains is the way to go.

2
12/4/2017 6:17:58 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow