Click here to Skip to main content
15,891,758 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi guys. I am a new learner of C#. I have an error like this in my code :
Severity	Code	Description	Project	File	Line	Suppression State
Error	CS1503	Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<TEntity, bool>>' to 'System.Linq.Expressions.Expression<System.Func<TContext, int, bool>>'

I am taking this error because of filter predicate in where command. I couldn't solve. What can i do ?
Code i wrote:
C#
public List<TEntity> GetList(Expression<Func<TEntity, bool>> filter = null)
        {
            using(var context = new TContext())
            {
                return filter == null ? context.Set<TContext>().ToList() : context.Set<TContext>().Where(filter).ToList();
            }
        }


Thanks!!

What I have tried:

I tried to write like this:
public List<TEntity> GetList(Expression<Func<TEntity,int, bool>> filter = null)
        {
            using(var context = new TContext())
            {
                return filter == null ? context.Set<TContext>().ToList() : context.Set<TContext>().Where(filter).ToList();
            }
        }


But the error has not changed.
Posted
Updated 12-Jul-20 7:04am
v2

1 solution

I am going to assume TContext is an Entity Framework DbContext and TEntity is an EF Entity.

The "Set" method returns a dataset from that table;

C#
context.Set<TContext>().Where(filter).ToList();


So you are getting a list of TContext items from the table that holds TContext items. You are then doing a Where using the filter, but the filter is an expression that works on TEntity items

C#
Expression<Func<TEntity, bool>> filter


so you are trying to filter TContext items by properties on TEntity and the two don't match. This is all ignoring the elephant in the room that you are using "Set" on a db context so that doesn't work anyway. I think what you meant to write was this;

C#
public List<TEntity> GetList(Expression<Func<TEntity, bool>> filter = null)
        {
            using(var context = new TContext())
            {
                return filter == null ? context.Set<TEntity>().ToList() : context.Set<TEntity>().Where(filter).ToList();
            }
        }


Now the code makes sense as you are requesting a set of entities from a table and then filtering that list using an expression that relates to the entity. Now your types all match and make sense.
 
Share this answer
 
Comments
||Memo|| 12-Jul-20 15:06pm    
I think you're hero, Thanks!
BillWoodruff 12-Jul-20 17:01pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900