I have the following (greatly abridged) generic repository class:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private DbSet<TEntity> _entitySet;
private NewExternalsContext _dbContect;
public Repository(NewExternalsContext dbContext)
{
_dbContect = dbContext;
_entitySet = _dbContect.Set<TEntity>();
}
public virtual TEntity Get(object objectId)
{
// TODO Figure out how to use 'id' to build an Expression<Func<TEntity, bool>>.
throw new NotImplementedException();
}
public virtual TEntity FindOne(Expression<Func<TEntity, bool>> where)
{
return _entitySet.FirstOrDefault(where);
}
}
My problem with the public virtual TEntity Get(object objectId)
method is that because the repository is generic, I don't know that TEntity
has any id field, or what it is called. The best I can do is check if it has an Id
field, my most common name for id fields. Then, how do I e.g. do say _entitySet.Where("Id = " + objectId)
? I have the public virtual TEntity FindOne(Expression<Func<TEntity, bool>> where)
method, but when I just want to get an object by id
, as is so common, I don't want to write out a whole lambda expression.