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);
}
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>();
}
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.