简体   繁体   中英

Entity Framework - Get Records : Comma separated string (or List<string>) is contained within a collection of entities

Given entities

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public ICollection<Category> Categories { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public ICollection<Product> Products { get; set; }
}

I want to query the Products table to retrieve products with any of the categories given as a comma separated list.

So, for example I want to get products with categories "Electronics" AND/OR "Kitchen Equipment"

If it wasn't a collection, I would do like this: Eg

Products.Where(p => "Oven,Kettle".Contains(p.ProductName));

But this obviously does not work:

Products.Where(p => "Electronics,Kitchen Equipment".Contains(p.Categories.CategoryName));

also tried:

Products.Where(p => "Electronics,Kitchen Equipment".Any(x => p.Categories.Any(pcat => pcat.CategoryName == x.ToString()))).Take(100);

You have to pass IEnumerable into Where clause:

var names = "Oven,Kettle".Split(',');
var query = Products.Where(p => names.Contains(p.ProductName));
var categories = new[] { "Electronics", "Kitchen Equipment" };

var productsQuery = Products
    .Where(p => p.Categories.Any(pcat => categories.Contains(pcat.CategoryName))
    .Take(100);

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.

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