1

I have this method for my Entity Framework class (v6) to get all the elements in this table from my database:

List<FooClass> GetAll_FooClass()
{
    return dbContext.FooClass.ToList();
}

So what I would like is a method which would do the same but would be usable on each entity class I have (individually I mean).

Is it possible and if so, how can I implement it ?

EDIT: I seem to have mistaken FooClass for a class whereas it is a property of the dbContext object.

public class MyDbContext : DbContext
{
    public MyDbContext()
    { }

    public virtual DbSet<FooClass> FooClass { get; set; }
}

So I'm trying to use System.Type right now (PropertyInfo and MethodInfo).

4
  • 6
    dbContext.Set<TypeOfEntity>().ToList()? Commented Jun 6, 2018 at 15:00
  • 3
    Use @DavidG answer and make your current method generic Commented Jun 6, 2018 at 15:03
  • Side note => I think you might look at some coding conventions because naming like GetAll_myEntityClass is so... Commented Jun 6, 2018 at 15:38
  • I tried what @DavidG suggested and got this notification from Visual Studio: 'DbContext.Set<TEntity>' is a method, which is not valid in the given context. So I confused the current FooClass which is a property whithin MyDbContext class with the entity class it is named after: public class MyDbContext : DbContext { public virtual DbSet<FooClass> FooClass { get; set; } } Commented Jun 7, 2018 at 8:41

1 Answer 1

4

You can use a generic method that takes the type of the entity. For example:

public List<TEntity> GetAll<TEntity>() 
    where TEntity : class //This is important as the Set method requires it
{
    //Obviously don't do this, but for completeness:
    var dbContext = new MyContext();

    //And here is the real 'magic':
    return dbContext.Set<TEntity>().ToList();
}

To use it, assuming you have a context that looks something like this:

public class MyContext : DbContext
{
    public DbSet<Zombie> Zombies { get; set; }
    public DbSet<Human> Humans { get; set; }
}

You would call it like this:

var allOfTheZombies = GetAll<Zombie>();
Sign up to request clarification or add additional context in comments.

2 Comments

Well, now it's working. I don't know what's different (maybe I forgot to use "where T : class"). Thank you !
I just have to see how to get it working with a mocked (Moq) context in my unit test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.