Reputation:
I am working on a new web application using ASP.Net 5 / EF7.
I am also considering the Repository Pattern along with Entity Framework.
I am looking for some advice to deal with my generic repository class. As EF7 has no Find() method to yet, I am having some difficulties implementing the method like GetById(int id) in my generic repository class. I know that can use FirstOrDefault() instead, but I do not have access to the actual 'Id' from the model.
Can you please help me to find an alternative?
Below is my generic repository class:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly PersonDBContext _dbContext;
public Repository(PersonDBContext context)
{
_dbContext = context;
}
public IEnumerable<TEntity> GetAll()
{
return _dbContext.Set<TEntity>().ToList();
}
public TEntity Get(int? id)
{
return _dbContext.Set<TEntity>().FirstOrDefault();
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return _dbContext.Set<TEntity>().Where(predicate);
}
public void Add(TEntity entity)
{
_dbContext.Set<TEntity>().Add(entity);
}
public void Remove(TEntity entity)
{
_dbContext.Set<TEntity>().Remove(entity);
}
}
Thanks Saeed
Upvotes: 2
Views: 1338
Reputation: 247173
Here is something you can try.
Based on your comment that you don't know the actual id of the model then use an expression like you did with the Find
to get the entity you are looking for.
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class {
//.....
public TEntity Get(Expression<Func<TEntity, bool>> predicate)
{
return _dbContext.Set<TEntity>().FirstOrDefault(predicate);
}
//.....
}
Upvotes: 1
Reputation: 4456
I have created a post in my blog that explains how to create a generic repository, you can check it at Generic Repository using EntityFramework
You Will have to add another parameter to your generic interface, instead of having only the Entity Type, you can pass also the Primary Key type and also you can use a base class
Upvotes: 1