此时,我们需要将这个实体从业务层(BLL)传递到数据访问层(DAL),当GetModel方法返回实体后会立即释放掉DataContext,然后到了执行DAL.Update(Entity entity)方法时又重新实例化一个DataContext来进行更新操作;可见被传递的实体是从第一个DataContext传递到另一个DataContext,在LINQ TO SQL中这种跨越不同DataContext操作时,需要先进行附加操作,也就是context.Entity.Attach(entity,true); 最后再context.SubmitChanges();
还是看看代码吧:
代码 class BLL { PRivate readonly DAL dal = new DAL(); public LinqToSqlProvider.User GetModel(Expression<Func<LinqToSqlProvider.User, bool>> expression) { dal.GetModel(expression); } public void Update(LinqToSqlProvider.User entity) { dal.Update(entity); } }
class DAL {
public LinqToSqlProvider.User GetModel(Expression<Func<LinqToSqlProvider.User, bool>> expression) { LinqToSqlProvider.User entry = new CriTextBroadcast.LinqToSqlProvider.User(); using (CriTextBroadcastDBDataContext context = DataContext) { entry = context.User.SingleOrDefault(expression); } return entry; }
public void Update(LinqToSqlProvider.User entity) { using (CriTextBroadcastDBDataContext context = DataContext) { context.User.Attach(entry, true); context.SubmitChanges(); } } }