linq to sql统一更新方法,直接返回更新的对象(解决更新后再刷新数据错误显示问题)

   /// <summary>
        /// 通过主键,得到实体
        /// 始终从数据库中获取数据
        /// </summary>
        /// <param name="keyValues"></param>
        /// <returns></returns> 

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();
            TEntity entity = this.DbSet.Where(String.Join(" && ", keys), keyValues).FirstOrDefault();
            this._db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, entity);
            return entity;
        }

 

   /// <summary>
        ///  更新实体
        /// </summary>
        /// <param name="entity"></param>

 public void Update(TEntity entity)
        {
            TEntity originalEntity = this.Find(entity.PrimaryKey);
            if (originalEntity == null)
                this._db.GetTable<TEntity>().InsertOnSubmit(entity);
            else
                EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<TEntity, TEntity>().Map(entity, originalEntity);
            base.SubmitChanges();
        }

posted @ 2011-11-15 03:50  张占岭  阅读(917)  评论(0编辑  收藏  举报