Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Entity Framework type to generic method

In my project using Entity Framework, I have a bunch of functions that look almost exactly alike, so I want to created a generic method they call:

private IHttpActionResult GetData<TEntity>(DbSet<TEntity> data) 

The problem I'm having is that the data parameter is saying TEntity has to be a reference type to work, but the type of the entity comes from auto-generated code that doesn't have any base class that I can constrain via a where clause on the method definition.

I'd basically want to call it by getting a context and passing the table in like so:

using (var context = new DataModel.MyEntities()) {
    GetData(context.Lab_SubSpace_Contact);
}
like image 298
Gargoyle Avatar asked Dec 14 '25 18:12

Gargoyle


1 Answers

To expand on @Igor's answer, you don't have to pass the DbSet<TEntity>, you can also get that dynamically through the type parameter:

private IHttpActionResult GetData<TEntity>() where TEntity : class
{
    using (var context = new YourContext())
    {
        var dbSet = context.Set<TEntity>();
    }
}
like image 77
Camilo Terevinto Avatar answered Dec 16 '25 10:12

Camilo Terevinto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!