How to filter in one-to-many relationship tables in LINQ?

entity-framework-core linq

Question

I have EVENTS and CATEGORY table. One event may have more than one Category associated. So it is one to many.

When I try to filter CATEGORY table I am getting error ArgumentException: The property expression i => i.Category.CategoryName.Contains("Social") is not valid. The expression should represent a property access: t => t.MyProperty. For more information on including related data, see Loading Related Data .

Here is my code

   var viewModel = new EventIndexData();
            viewModel.Events = await _context.Events
                                 .Include(i => i.Categories)
                                    .ThenInclude(i => i.Category.CategoryName.Contains("Social"))
                                    .AsNoTracking()
                                 .ToListAsync();

any help appreciated !

1
0
12/10/2016 5:22:07 AM

Popular Answer

You need first to create a query and append condition:

var categoryName = "Social";

var query = _context.Events.Include(i => i.Category);

if (String.IsNullOrEmpty(categoryName))
{
    query = query.Where(item => item.Category.CategoryName.Contains(categoryName));
}

var viewModel = new EventIndexData();

viewModel.Events = await query.ToListAsync();

I'm not sure about your objects name, but you can fix in your code.

0
12/10/2016 6:14:10 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