James Andrew Smith
James Andrew Smith

Reputation: 1566

Pass entity type through method in EF

Hi I want to produce a generic linq query that gets the required drop down information from the database. I want to be able to specify the entity i want to get data from within the context.

e.g.

public IEnumerable<T> getListOfDropdowns(int assignId, TEntity entityname)
{
    return context.<TEntity>.Where(x => x.assignId == 1);
}

All lookup tables contain the same properties. eg. ID and Description.

I now have

public IQueryable<T> GetLookupByContractorTwo<TEntity>(int contractorId, TEntity entity)
{
return _context.Set<entity>().Find(contractorId);
}

But I get an error saying entity cannot be found and missing a referencbut i am unable to find the reference.

Upvotes: 0

Views: 142

Answers (2)

thepirat000
thepirat000

Reputation: 13114

Try with this:

public IQueryable<TEntity> GetLookupByContractorTwo<TEntity>(int contractorId)
{
    return _context.Set<TEntity>().Find(contractorId);
}

You don't need to pass the Type as a parameter if you're using generics.


Edit

You probably want to do this:

public IQueryable<T> GetLookupByContractorTwo<TEntity>(int contractorId)
{
  return _context.Set(typeof(TEntity)).Find(contractorId);
}

Upvotes: 1

MaxSC
MaxSC

Reputation: 4758

You could use the Findmethod instead. Find uses the primary key to search.
Another good thing about Find is that it will perform a round-trip to the database only if the entity is not found in the context.

This should do the trick:

var result = context.Set<TEntity>().Find(assignId);

Upvotes: 0

Related Questions