Answer the question
In order to leave comments, you need to log in
Are the "Session" and "Repository" patterns implemented correctly?
Hello. For some time I have been implementing the "Repository" pattern following the example from Sanderson's book "ASP.NET MVC Framework with C# Examples for Professionals", but recently I came to the idea of its inefficiency, I consider the main disadvantages:
- the need to write for each type of entity own repository with almost identical code;
- saving the database context after each action, as a result - a large number of calls to the database.
After reading articles about designing sessions and repositories, I wrote the following implementation (I threw out part of the code for greater clarity):
public class Session : IDisposable
{
private readonly DatabaseContext context = new DatabaseContext();
public Repository<T> Repository<T>() where T : EntityBase, new()
{
return new Repository<T>(context);
}
public void Commit()
{
context.SaveChanges();
}
public void Dispose()
{
if (this.context != null)
this.context.Dispose();
}
}
public class Repository<TEntity> where TEntity : EntityBase, new()
{
private readonly DbSet<TEntity> entities;
public TEntity Create()
{
var entity = new TEntity();
this.Add(entity);
return entity;
}
public TEntity Get(int entityId)
{
return this.entities.Find(entityId);
}
public IEnumerable<TEntity> GetAll()
{
return this.entities.AsEnumerable();
}
public void Add(TEntity entity)
{
this.entities.Add(entity);
}
public void Delete(int entityId)
{
var deletedEntity = this.entities.Find(entityId);
if (deletedEntity != null)
this.entities.Remove(deletedEntity);
}
public Repository(DbContext context)
{
this.entities = context.Set<TEntity>();
}
}
protected void SaveEntity<TEntity>(TEntity entity) where TEntity : EntityBase, new()
{
using (var session = new Session())
{
session.Repository<TEntity>().AddOrUpdate(entity);
session.Commit();
}
}
Answer the question
In order to leave comments, you need to log in
In my opinion, the use of these patterns for EF is unnecessary.
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit.
msdn.microsoft.com
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question