3

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);
}
3
  • 1
    private IHttpActionResult GetData<TEntity>(DbSet<TEntity> data) where TEntity : class <=== Why can't you do that? Commented Mar 15, 2018 at 21:56
  • When it says the TEntity has to be a reference type it means that as an unconstrained generic type it can be either a reference or a value type. Igor has given you the constraint that will limit the generic type to a reference types class. Commented Mar 15, 2018 at 21:58
  • Cause I didn't realize I could just do that :) It won't let me accept your answer for 9 more minutes. Thanks for the quick solution. Commented Mar 15, 2018 at 21:59

2 Answers 2

3

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>();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very cool! This definitely makes the DB connection cleaner too.
2

You do not need a base class, you only have to specify a constraint that it has to be a class (not a struct). This can be done with where TEntity : class

Constraints on Type Parameters

where T : class : The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

Modified code

private IHttpActionResult GetData<TEntity>(DbSet<TEntity> data) where TEntity : class

Comments

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.