Pindakaas
Pindakaas

Reputation: 4439

c# how to convert code into a generic version?

I am trying to write this code in a more generic fashion:Is it possible that based on T i can use the right entityframework entity? So for example if I would use :

public IQueryable<T> GetCount(string filterExpression)
{
   //return db.Persons.Where("it." + filterExpression);
   return db. ? .Where("it." + filterExpression); // depending on type T
}

UPDATE

so now I did this:

  public int GetCount<T>(string filter)
        where T : class
        {
            NortwindEntities db = new NortwindEntities();
            return db.CreateObjectSet<T>().Where(filter).Count();
        }

error:

Error   2   The constraints for type parameter 'T' of method 'MyBase<T>.GetCount<T>(string)' must match the constraints for type parameter 'T' of interface method 'MyBase<T>.GetCount<T>(string)'. Consider using an explicit interface implementation instead

Upvotes: 1

Views: 134

Answers (1)

dknaack
dknaack

Reputation: 60506

Are you sure that you want a queryable of T? (the name of your method is GetCount.)

You can do this to get a IQueryable<T> from your DbContext.

public IQueryable<T> GetCount<T>(Func<T, bool> predicate)
    where T : class
{
    MyContext db = new MyContext();
    return db.Set<T>().Where(predicate).AsQueryable();
}

IQueryable<Person> result = GetCount<Person>(x => x.Id == 1);

I suggest to use the name Where as your method name.

public IQueryable<T> Where<T>(Func<T, bool> predicate)
    where T : class
{
    MyContext db = new MyContext();
    return db.Set<T>().Where(predicate).AsQueryable();
}

IQueryable<Person> result = Where<Person>(x => x.Id == 1);

Update

Decorate the method with where T : class if you get the following exception.

The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method ?

Update 2

Seems that you really only want the count.

public int GetCount<T>(Func<T, bool> predicate)
    where T : class
{
    MyContext db = new MyContext();
    return db.Set<T>().Where(predicate).Count();
}

int count = GetCount<Person>(x => x.Id == 1);

Upvotes: 1

Related Questions