MVC+LINQToSQL的Repository模式之(二)数据基类

namespace Data.TEST
{
    /// <summary>
    /// 数据操作基类
    /// </summary>
    public abstract class TESTRepositoryBase
    {
        /// <summary>
        /// 数据库基类
        /// </summary>
        protected Entity.TEST.LinqTESTDataContext _db = (Entity.TEST.LinqTESTDataContext)DbFactory.Intance("TEST", System.Threading.Thread.CurrentThread);
        /// <summary>
        /// 统一提交动作
        /// </summary>
        protected virtual void SubmitChanges()
        {
            ChangeSet cSet = _db.GetChangeSet();
            if (cSet.Inserts.Count > 0
                || cSet.Updates.Count > 0
                || cSet.Deletes.Count > 0)
            {
                try
                {
                    _db.SubmitChanges(System.Data.Linq.ConflictMode.ContinueOnConflict);
                }
                catch (System.Data.Linq.ChangeConflictException ex)
                {
                    foreach (System.Data.Linq.ObjectChangeConflict occ in _db.ChangeConflicts)
                    {
                        // 使用当前数据库中的值,覆盖Linq缓存中实体对象的值 
                        occ.Resolve(System.Data.Linq.RefreshMode.OverwriteCurrentValues);
                        // 使用Linq缓存中实体对象的值,覆盖当前数据库中的值 
                        occ.Resolve(System.Data.Linq.RefreshMode.KeepCurrentValues);
                        // 只更新实体对象中改变的字段的值,其他的保留不变 
                        occ.Resolve(System.Data.Linq.RefreshMode.KeepChanges);
                    }
                    _db.SubmitChanges();
                }
            }
        }
    }
}

posted @ 2011-11-08 13:34  张占岭  阅读(1725)  评论(0编辑  收藏  举报