0

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.

ProfK
  • 49,207
  • 121
  • 399
  • 775
  • 1
    The DbSet class has a [Find method](http://msdn.microsoft.com/en-us/library/gg696418(v=vs.103).aspx) which does what you want. It finds entities based on the primary key. – nemesv Mar 10 '13 at 12:24

1 Answers1

0

You will need to create another method that returns you an entity as in this question: How to get ObjectSet<T>'s entity key name?, you can cheat a little and get the entity by id as below:

    public T GetById(int id)
    {
        var keyPropertyName =_objectSet.EntitySet.ElementType.KeyMembers[0].ToString();          
        T entity = _objectSet.Where("it." + keyPropertyName + "=" + id).First();
        return entity;
    }
Community
  • 1
  • 1
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
  • Thank you, but other reading says it's as impossible to convert a DdSet to an ObjectSet, and I'm using DbSets. Otherwise this looks cool. – ProfK Mar 12 '13 at 20:27