MVC+LINQToSQL的Repository模式之(三)Repository模式实现统一CURD操作,实现EF中的Find主键查找

namespace Data.TEST

{

    /// <summary>

    /// 数据通用操作实现

    /// </summary>

    /// <typeparam name="TEntity"></typeparam>

    public class Repository<TEntity> : TESTRepositoryBase, IRepository<TEntity> where TEntity : class,IEntity

    {

        #region IRepository<TEntity> 成员



        public void Update(TEntity entity)

        {

            TEntity originalEntity = this.Find(entity.PrimaryKey);

            EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<TEntity, TEntity>().Map(entity, originalEntity);

            base.SubmitChanges();

        }



        public void Update(IList<TEntity> list)

        {

            TEntity originalEntity = null;

            list.ToList().ForEach(entity =>

            {

                originalEntity = this.Find(entity.PrimaryKey);

                EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<TEntity, TEntity>().Map(entity, originalEntity);

            });

            base.SubmitChanges();

        }



        public void Insert(TEntity entity)

        {

            this._db.GetTable<TEntity>().InsertOnSubmit(entity);

            base.SubmitChanges();

        }



        public void Insert(IList<TEntity> list)

        {

            list.ToList().ForEach(entity =>

            {

                this._db.GetTable<TEntity>().InsertOnSubmit(entity);

            });

            base.SubmitChanges();

        }



        public TEntity InsertGetIDENTITY(TEntity entity)

        {

            this._db.GetTable<TEntity>().InsertOnSubmit(entity);

            base.SubmitChanges();

            return this.Find(entity.PrimaryKey);

        }



        public void Delete(TEntity entity)

        {

            this._db.GetTable<TEntity>().DeleteOnSubmit(entity);

            base.SubmitChanges();

        }



        public IQueryable<TEntity> GetModel()

        {

            this._db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, this.DbSet);//解决频繁刷新数据问题

            return this.DbSet;

        }



        public TEntity Find(params object[] keyValues)

        {

            var mapping = _db.Mapping.GetTable(typeof(TEntity));

            var keys = mapping.RowType.IdentityMembers.Select((m, i) => m.Name + " = @" + i).ToArray();

            return this.DbSet.Where(String.Join(" && ", keys), keyValues).FirstOrDefault();

        }



        /// <summary>

        /// 泛型数据表属性

        /// </summary>

        private IQueryable<TEntity> DbSet

        {



            get

            {

                return this._db.GetTable<TEntity>();

            }



        }

        #endregion

    }

}

 

 

你可能感兴趣的:(repository)