namespace MyRepository.Domain.Infrastructure
{
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected BookStoreDbContext dbContext;
protected DbSet<TEntity> dbSet; public Repository(BookStoreDbContext dbContext)
{
this.dbContext = dbContext;
this.dbSet = dbContext.Set<TEntity>();
}
public void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public void Update(TEntity entity)
{
dbSet.Attach(entity);
dbContext.Entry(entity).State = EntityState.Modified;
}
public void Delete(TEntity entity)
{
if (dbContext.Entry(entity).State == EntityState.Detached)
{
dbSet.Attach(entity);
}
dbSet.Remove(entity);
}
}
} /// <summary>
    /// 用于对数据的保存操作
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        private  readonly BookStoreDbContext _context;
        public DbContext Context
        {
            get { return _context; }
        }         public event EventHandler Disposed;         public bool IsDisposed { get; private set; }
        public void Dispose()
        {
            Dispose(true);
        }
        public virtual void Dispose(bool disposing)
        {
            lock (this)
            {
                if (disposing && !IsDisposed)
                {
                    _context.Dispose();
                    var evt = Disposed;
                    if (evt != null) evt(this, EventArgs.Empty);
                    Disposed = null;
                    IsDisposed = true;
                    GC.SuppressFinalize(this);
                }
            }
        }         public UnitOfWork(BookStoreDbContext context)
        {
            _context = context;
        }         public void Save()
        {
            _context.SaveChanges();
        }         ~UnitOfWork()
        {
            Dispose(false);
        }
    }

http://www.cnblogs.com/zhongxinWang/archive/2012/02/22/2360283.html

05-11 22:21