/// <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();
}
本文转自博客园张占岭(仓储大叔)的博客,原文链接:linq to sql统一更新方法,直接返回更新的对象(解决更新后再刷新数据错误显示问题),如需转载请自行联系原博主。