直接来解决办法:
public partial class BaseDAL<T> where T:class { GzItcastEntities db = new GzItcastEntities(); /// <summary> /// 新增 /// </summary> /// <param name="model"></param> /// <returns></returns> public virtual T Add(T model) { db.Set<T>().Add(model); db.SaveChanges(); db.Entry<T>(model).State = EntityState.Detached; //增加这句可以解决问题 return model; } /// <summary> /// 根据条件查询一个实体对象 /// </summary> /// <param name="where"></param> /// <returns></returns> public virtual T GetModel(Expression<Func<T, bool>> where) { T model = db.Set<T>().Where(where).ToList().FirstOrDefault(); db.Entry(model).State = EntityState.Detached; //增加这句可以解决问题 return model; } }
说明:
vs2010才会抛出这个异常,2012不会
在vs2012 GzItcastEntities 默认继承于DbContext
在vs2010 GzItcastEntities 默认继承于ObjectContext
如果继承于 ObjectContext 请调用Detach()方法(未实验)
补充:又发现个新办法,将DbContext 存入Session中,
GzItcastEntities = DbContextHelper.GetDbContext() as GzItcastEntities ;
public static class DbContextHelper { private static DbContext db = null; private const string SessionKey_DbContext = "DbContext"; /// <summary> /// 获得DbContext /// </summary> /// <returns></returns> public static DbContext GetDbContext() { db = HttpContext.Current.Session[SessionKey_DbContext] as DbContext; if (db == null) { db = new GZRA_ADSP_DBEntities(); HttpContext.Current.Session[SessionKey_DbContext] = db; } return db; } }