For example, let say I have 4 different entity that each implement a Add() method that add the entity to the database :
public class Profile
{
...
publi
Try a generic repository, at the end you will develop something similar. You need 3 interfaces:
And the implementations to those interfaces:
Here the code:
IEntity.cs
public interface IEntity where TId : IComparable
{
TId Id { get; set; }
}
IEntityContext.cs
public interface IEntityContext : IDisposable
{
void SetAsAdded(TEntity entity) where TEntity : class;
void SetAsModified(TEntity entity) where TEntity : class;
void SetAsDeleted(TEntity entity) where TEntity : class;
IDbSet Set() where TEntity : class;
int SaveChanges();
}
IEntityRepository.cs
public interface IEntityRepository
: IDisposable
where TEntity : class, IEntity
where TId : IComparable
{
IQueryable GetAll(
Expression> where = null,
Expression> orderBy = null);
PaginatedList Paginate(int pageIndex, int pageSize);
TEntity GetSingle(TId id);
IQueryable GetAllIncluding(
Expression> where,
Expression> orderBy,
params Expression>[] includeProperties);
TEntity GetSingleIncluding(
TId id, params Expression>[] includeProperties);
void Add(TEntity entity);
void Attach(TEntity entity);
void Edit(TEntity entity);
void Delete(TEntity entity);
int Save();
}
EntityRepository.cs
public class EntityRepository
: IEntityRepository
where TEntity : class, IEntity
where TId : IComparable
{
private readonly IEntityContext _dbContext;
public EntityRepository(IEntityContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
_dbContext = dbContext;
}
public IQueryable GetAllIncluding(
Expression> where,
Expression> orderBy,
params Expression>[] includeProperties)
{
try
{
IQueryable queryable = GetAll(where, orderBy);
foreach (Expression> includeProperty in includeProperties)
{
queryable =
queryable.Include(includeProperty);
}
return queryable;
}
catch (Exception)
{
throw;
}
}
public TEntity GetSingleIncluding(
TId id,
params Expression>[] includeProperties)
{
try
{
IQueryable entities =
GetAllIncluding(null, null, includeProperties);
TEntity entity =
Filter(entities, x => x.Id, id).FirstOrDefault();
return entity;
}
catch (Exception)
{
throw;
}
}
public void Add(TEntity entity)
{
try
{
_dbContext.Set().Add(entity);
if (this.EntityAdded != null)
this.EntityAdded(this, new EntityAddedEventArgs(entity));
}
catch (Exception)
{
throw;
}
}
public void Attach(TEntity entity)
{
try
{
_dbContext.SetAsAdded(entity);
if (this.EntityAttach != null)
this.EntityAttach(this, new EntityAddedEventArgs(entity));
}
catch (Exception)
{
throw;
}
}
public void Edit(TEntity entity)
{
try
{
_dbContext.SetAsModified(entity);
if (this.EntityModified != null)
this.EntityModified(this, new EntityModifiedEventArgs(entity));
}
catch (Exception)
{
throw;
}
}
public void Delete(TEntity entity)
{
try
{
_dbContext.SetAsDeleted(entity);
if (this.EntityDeleted != null)
this.EntityDeleted(this, new EntityDeletedEventArgs(entity));
}
catch (Exception)
{
throw;
}
}
public int Save()
{
try
{
return _dbContext.SaveChanges();
}
catch (Exception)
{
throw;
}
}
public IQueryable GetAll(
Expression> where = null,
Expression> orderBy = null)
{
try
{
IQueryable queryable =
(where != null) ? _dbContext.Set().Where(where)
: _dbContext.Set();
return (orderBy != null) ? queryable.OrderBy(orderBy)
: queryable;
}
catch (Exception)
{
throw;
}
}
public TEntity GetSingle(TId id)
{
try
{
IQueryable entities = GetAll();
TEntity entity =
Filter(entities, x => x.Id, id).FirstOrDefault();
return entity;
}
catch (Exception)
{
throw;
}
}
public void Dispose()
{
_dbContext.Dispose();
}
#region Private
private IQueryable Filter(
IQueryable dbSet,
Expression> property, TProperty value)
where TProperty : IComparable
{
try
{
var memberExpression = property.Body as MemberExpression;
if (memberExpression == null ||
!(memberExpression.Member is PropertyInfo))
throw new ArgumentException
("Property expected", "property");
Expression left = property.Body;
Expression right =
Expression.Constant(value, typeof(TProperty));
Expression searchExpression = Expression.Equal(left, right);
Expression> lambda =
Expression.Lambda>(
searchExpression,
new ParameterExpression[] { property.Parameters.Single() });
return dbSet.Where(lambda);
}
catch (Exception)
{
throw;
}
}
private enum OrderByType
{
Ascending,
Descending
}
#endregion
}
EntityContext.cs
public abstract class EntityContext : DbContext, IEntityContext
{
///
/// Constructs a new context instance using conventions to create the name of
/// the database to which a connection will be made. The by-convention name is
/// the full name (namespace + class name) of the derived context class. See
/// the class remarks for how this is used to create a connection.
///
protected EntityContext() : base() { }
///
/// Constructs a new context instance using conventions to create the name of
/// the database to which a connection will be made, and initializes it from
/// the given model. The by-convention name is the full name (namespace + class
/// name) of the derived context class. See the class remarks for how this is
/// used to create a connection.
///
/// The model that will back this context.
protected EntityContext(DbCompiledModel model) : base(model) { }
///
/// Constructs a new context instance using the given string as the name or connection
/// string for the database to which a connection will be made. See the class
/// remarks for how this is used to create a connection.
///
/// Either the database name or a connection string.
public EntityContext(string nameOrConnectionString)
: base(nameOrConnectionString) { }
///
/// Constructs a new context instance using the existing connection to connect
/// to a database. The connection will not be disposed when the context is disposed.
///
/// An existing connection to use for the new context.
///
/// If set to true the connection is disposed when the context is disposed, otherwise
/// the caller must dispose the connection.
///
public EntityContext
(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection) { }
///
/// Constructs a new context instance around an existing ObjectContext. An existing
/// ObjectContext to wrap with the new context. If set to true the ObjectContext
/// is disposed when the EntitiesContext is disposed, otherwise the caller must dispose
/// the connection.
///
/// An existing ObjectContext to wrap with the new context.
///
/// If set to true the ObjectContext is disposed when the EntitiesContext is disposed,
/// otherwise the caller must dispose the connection.
///
public EntityContext(
ObjectContext objectContext,
bool EntityContextOwnsObjectContext)
: base(objectContext, EntityContextOwnsObjectContext)
{ }
///
/// Constructs a new context instance using the given string as the name or connection
/// string for the database to which a connection will be made, and initializes
/// it from the given model. See the class remarks for how this is used to create
/// a connection.
///
/// Either the database name or a connection string.
/// The model that will back this context.
public EntityContext(
string nameOrConnectionString,
DbCompiledModel model)
: base(nameOrConnectionString, model)
{ }
///
/// Constructs a new context instance using the existing connection to connect
/// to a database, and initializes it from the given model. The connection will
/// not be disposed when the context is disposed. An existing connection to
/// use for the new context. The model that will back this context. If set
/// to true the connection is disposed when the context is disposed, otherwise
/// the caller must dispose the connection.
///
/// An existing connection to use for the new context.
/// The model that will back this context.
///
/// If set to true the connection is disposed when the context is disposed, otherwise
/// the caller must dispose the connection.
///
public EntityContext(
DbConnection existingConnection,
DbCompiledModel model, bool contextOwnsConnection)
: base(existingConnection, model, contextOwnsConnection)
{ }
public new IDbSet Set() where TEntity : class
{
try
{
return base.Set();
}
catch (Exception)
{
throw;
}
}
public void SetAsAdded(TEntity entity) where TEntity : class
{
try
{
DbEntityEntry dbEntityEntry = GetDbEntityEntrySafely(entity);
dbEntityEntry.State = EntityState.Added;
}
catch (Exception)
{
throw;
}
}
public void SetAsModified(TEntity entity) where TEntity : class
{
try
{
DbEntityEntry dbEntityEntry = GetDbEntityEntrySafely(entity);
dbEntityEntry.State = EntityState.Modified;
}
catch (Exception)
{
throw;
}
}
public void SetAsDeleted(TEntity entity) where TEntity : class
{
try
{
DbEntityEntry dbEntityEntry = GetDbEntityEntrySafely(entity);
dbEntityEntry.State = EntityState.Deleted;
}
catch (Exception)
{
throw;
}
}
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (Exception)
{
throw;
}
}
public new void Dispose()
{
try
{
base.Dispose();
}
catch (Exception)
{
throw;
}
}
#region Private
private DbEntityEntry GetDbEntityEntrySafely(
TEntity entity) where TEntity : class
{
try
{
DbEntityEntry dbEntityEntry = base.Entry(entity);
if (dbEntityEntry.State == EntityState.Detached)
Set().Attach(entity);
return dbEntityEntry;
}
catch (Exception)
{
throw;
}
}
#endregion
}
Long Answer but worth it... Have a nice day :) Its part of a personal huge project :D