MVC+LINQToSQLのRepositoryモードの(三)Repositoryモード統一CURD操作を実現し、EF中のFind主キー検索を実現する

6815 ワード

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

    }

}