码迷,mamicode.com
首页 > 其他好文 > 详细

Repository

时间:2014-11-28 15:43:12      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   color   os   sp   on   数据   

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

 

Repository

标签:style   blog   http   ar   color   os   sp   on   数据   

原文地址:http://www.cnblogs.com/shiningrise/p/4128482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!