110,535
社区成员
发帖
与我相关
我的任务
分享
public string UpdateClass(Guid id, string name)
{
using (SampleDataContext context = new SampleDataContext())
{
try
{
var p = context.Classes.SingleOrDefault(c => c.id == id);
p.name = name;
context.SubmitChanges();
return "Success";
}
catch (ChangeConflictException)
{
foreach (ObjectChangeConflict cc in context.ChangeConflicts)
{
ClassEntity c = (ClassEntity)cc.Object;
//放弃当前更新,所有更新以原先更新为准
cc.Resolve(RefreshMode.OverwriteCurrentValues);
}
return "This record has been changed by other user";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
// 调用的时候
H(ctx => UpdateClass(ctx, id, name));
// 原始方法只包含业务
public void UpdateClass(SampleDataContext context, Guid id, string name)
{
var p = context.Classes.SingleOrDefault(c => c.id == id);
p.name = name;
context.SubmitChanges();
}
// 处理异常的逻辑
public string H(Action<Context> action)
{
using (var context = new SampleDataContext())
{
try
{
action(context);
return "Success";
}
catch (ChangeConflictException)
{
foreach (ObjectChangeConflict cc in context.ChangeConflicts)
{
ClassEntity c = (ClassEntity)cc.Object;
cc.Resolve(RefreshMode.OverwriteCurrentValues);
}
return "This record has been changed by other user";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
这是最简单的封装,当然也能写的更复杂,支持更多的场景,比如像mvc或者WebApi框架里的Filter那种形式。不过自己写还是很费劲的,不如直接用工具生成代理。