I have written 3 repositories with the same format. How do I create a generic repository?
public class MyRepository : MyDataRepositoryBase<ASD>
{
protected override ASD AddEntity(MyDataContext entityContext, ASD entity)
{
return entityContext.ASDSet.Add(entity);
}
protected override IEnumerable<ASD> GetEntities(MyDataContext entityContext)
{
return from e in entityContext.ASDSet
select e;
}
}
This is where I am so far...
public class ComponentsRepository<T, U>:MyDataRepositoryBase<T>
where T : class,new()
where U : DbSet<U>, new()
{
protected override T AddEntity(MyDataContext entityContext, T entity)
{
return entityContext.U.Add(entity);
}
}
I am basically trying to find a way to call the DbSet "entityContext.ASDSet" without knowing what it is.
Any ideas or should I just let it go...
Entity Framework has a Set Method so you could do this
return entityContext.Set<T>().Add(entity);
But it won't check that you are passing in a class that isn't mapped. So it's use at your own risk, will throw an exception if it's not mapped. We have a base class that all our entity inherit from so we put a constraint on that, but even that there is no guarantee that a class is mapped in entity framework.
For what it's worth the generic repository is considered an anti-pattern. This is the implementation I used to use:
public class Repository<T> : IRepository<T> where T : class
{
private readonly IDbContext _context;
private readonly IDbSet<T> _dbSet;
public Repository(IDbContext context) {
_context = context;
_dbSet = context.Set<T>();
}
public void Add(T entity) {
_dbSet.Add(entity);
}
public void Update(T entity) {
_context.Entry(entity).State = EntityState.Modified;
}
...
}
My IDbContext:
public interface IDbContext
{
IDbSet<T> Set<T>() where T : class;
DbEntityEntry Entry<T>(T entity) where T : class;
int SaveChanges();
...
}
I used this with a UnitOfWork that I did my saving through and repository retrieval. That said, I really do find creating repositories around my entities a lot cleaner.
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.