IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tblName' AND COLUMN_NAME = 'ColumnName')
BEGIN
ALTER TABLE tblName ADD ColumnName nvarchar(60)
ENDpublic interface IUnitOfWork
{
IGenericRepository<T> RepositoryFor<T>() where T : class;
void SaveChanges();
}
public class UnitOfWork : IUnitOfWork, System.IDisposable
{
private readonly NORTHWNDEntities _context;
public UnitOfWork(NORTHWNDEntities context)
{
_context = context;
}
public IGenericRepository<T> RepositoryFor<T>() where T : class
{
return new GenericRepository<T>(_context);
}
public void SaveChanges()
{
_context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing){
if (!this.disposed){
if (disposing){
_context.Dispose();
}
}
this.disposed = true;}
public void Dispose(){
Dispose(true);System.GC.SuppressFinalize(this);}
}
IGenericRepository:-public interface IGenericRepository<TEntity>{
TEntity GetById(object id);TEntity GetFirstOrDefault(
void Insert(TEntity entity);void Update(TEntity entity);void Delete(object id);List<TEntity> GetAll();}
GenericRepository:-public class GenericRepository<TEntity> : IGenericRepository<TEntity> whereTEntity : class{
private DbContext context;private DbSet<TEntity> dbSet;public GenericRepository(DbContext context){
this.context = context;this.dbSet = context.Set<TEntity>();}public virtual TEntity GetById(object id){
return dbSet.Find(id);}
public virtual TEntity GetFirstOrDefault(Expression<Func<TEntity, bool>>filter = null, params Expression<Func<TEntity, object>>[] includes){
IQueryable<TEntity> query = dbSet;foreach (Expression<Func<TEntity, object>> include in includes)query = query.Include(include);
return query.FirstOrDefault(filter);}
public virtual void Insert(TEntity entity){
dbSet.Add(entity);
}
public virtual void Update(TEntity entity){
dbSet.Attach(entity);
context.Entry(entity).State = EntityState.Modified;}
public virtual void Delete(object id){
TEntity entityToDelete = dbSet.Find(id);
if (context.Entry(entityToDelete).State == EntityState.Detached){
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual List<TEntity> GetAll(){
return dbSet.ToList<TEntity>();}
}