none
更新记录的时候,ObjectStateManager 中已存在具有同一键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象 RRS feed

  • 问题

  • 头一回使用EF4.1做项目,在对数据层进行封装后,进行修改时,发现了标题上描述的问题。目标有办法解决,但是有违了数据的封装性。

    上代码:

    CDbContext:

    public class CDbContext : DbContext
        {
            private readonly static string CONNECTION_STRING = "name=CMIIMS_ConnString";
            public CDbContext()
                : base(CONNECTION_STRING)
            {
    
            }
    
            public DbSet<CCountry> CountrySet { get; set; }
            public DbSet<CProvince> ProvinceSet { get; set; }
            public DbSet<CCity> CitySet { get; set; }
            public DbSet<CTown> TownSet { get; set; }
            public DbSet<CGroup> GroupSet { get; set; }
            public DbSet<CCompany> CompanySet { get; set; }
            public DbSet<CDepartment> DepartmentSet { get; set; }
            public DbSet<CUser> UserSet { get; set; }
            public DbSet<CRole> RoleSet { get; set; }
            public DbSet<CSubSystem> SubSystemSet { get; set; }
            public DbSet<CMenu> MenuSet { get; set; }
            public DbSet<CController> ControllerSet { get; set; }
            public DbSet<CAction> ActionSet { get; set; }
            public DbSet<CLimit> LimitSet { get; set; }
            public DbSet<CGroupType> GroupTypeSet { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                //移除复数表名的契约;
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
                ////防止黑幕交易 要不然每次都要访问 EdmMetadata这个表;
                //modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
    
                //modelBuilder.Entity<CUser>().HasOptional(x => x.Department);
                //modelBuilder.Entity<CDepartment>().HasOptional(x => x.Company);
                //modelBuilder.Entity<CCompany>().HasOptional(x => x.Group);
                //modelBuilder.Entity<CGroup>().HasOptional(x => x.Town);
                //modelBuilder.Entity<CTown>().HasOptional(x => x.City);
                //modelBuilder.Entity<CCity>().HasOptional(x => x.Province);
    
                modelBuilder.Entity<CRole>().HasMany(c => c.Users).WithMany(i => i.Roles)
                    .Map(t => t.MapLeftKey("UserID").MapRightKey("RoleID").ToTable("TXTS_UserRole"));
    
                modelBuilder.Entity<CAction>().HasMany(c => c.Limits).WithMany(i => i.Actions)
                    .Map(t => t.MapLeftKey("ActionID").MapRightKey("LimitID").ToTable("TXTS_ActionLimit"));
    
                modelBuilder.Entity<CController>().HasMany(c => c.Limits).WithMany(i => i.Controllers)
                    .Map(t => t.MapLeftKey("ControllerID").MapRightKey("LimitID").ToTable("TXTS_ControllerLimit"));
    
                modelBuilder.Entity<CSubSystem>().HasMany(c => c.Limits).WithMany(i => i.SubSystems)
                    .Map(t => t.MapLeftKey("SubSystemID").MapRightKey("LimitID").ToTable("TXTS_SubSystemLimit"));
    
                modelBuilder.Entity<CMenu>().HasMany(c => c.Limits).WithMany(i => i.Menus)
                    .Map(t => t.MapLeftKey("MenuID").MapRightKey("LimitID").ToTable("TXTS_MenuLimit"));
            }
    
    
    


     

    IGenericRpository接口

    public interface IGenericRepository<TEntity> where TEntity : CBase
        {
            IEnumerable<TEntity> Get(
                Expression<Func<TEntity, bool>> filter = null,
                Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                string includeProperties = "");
    
            TEntity GetByID(object id);
    
            void Insert(TEntity entity);
    
            void Delete(object id);
    
            void Delete(TEntity entityToDelete);
    
           <strong> void Update(TEntity entityToUpdate);
    
    </strong>        IEnumerable<TEntity> GetWithRawSql(
                string query, params object[] parameters);
    
            int ExecSql(
                string strsqlCom, params object[] parameters);
        }
    
    
    

    CGenericRepository

    public class CGenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : CBase
        {
            public CDbContext context;
            public DbSet<TEntity> dbSet;
    
            public CGenericRepository(CDbContext context)
            {
                this.context = context;
                this.dbSet = context.Set<TEntity>();
            }
    
            public virtual IEnumerable<TEntity> Get(
                Expression<Func<TEntity, bool>> filter = null,
                Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                string includeProperties = "")
            {
                IQueryable<TEntity> query = dbSet;
    
                if (filter != null)
                {
                    query = query.Where(filter).Where(i => !i.IsDeleted);
                }
    
                foreach (var includeProperty in includeProperties.Split
                    (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    query = query.Include(includeProperty);
                }
    
                if (orderBy != null)
                {
                    return orderBy(query).ToList();
                }
                else
                {
                    return query.ToList();
                }
            }
    
            public virtual TEntity GetByID(object id)
            {
                return dbSet.Find(id);
            }
    
            public virtual void Insert(TEntity entity)
            {
                dbSet.Add(entity);
            }
    
            public virtual void Delete(object id)
            {
                TEntity entityToDelete = dbSet.Find(id);
                Delete(entityToDelete);
            }
    
            public virtual void Delete(TEntity entityToDelete)
            {
                if (context.Entry(entityToDelete).State == EntityState.Detached)
                {
                    dbSet.Attach(entityToDelete);
                }
                //dbSet.Remove(entityToDelete);
                entityToDelete.IsDeleted = true;
                Update(entityToDelete);
            }
    
            public virtual void Update(TEntity entityToUpdate)
            {
                dbSet.Attach(entityToUpdate);
                context.Entry(entityToUpdate).State = EntityState.Modified;
            }
    
            public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
            {
                return dbSet.SqlQuery(query, parameters).ToList();
            }
    
            public virtual int ExecSql(string strsqlCom, params object[] parameters)
            {
                return -1;
            }

    IUserRepository:

    public interface IUserRepository : IGenericRepository<CUser>
        {
            CUser ValidateLogon(string UserName, string hashed_pw);
        }
    
    

    CUserRepository:

    public class CUserRepository : CGenericRepository<CUser>, IUserRepository
        {
            public CUserRepository(CDbContext context) : base(context) { }
    
            public CUser ValidateLogon(string UserName, string hashed_pw)
            {
                return Get(i => i.UserName == UserName && i.Password == hashed_pw)
                    .FirstOrDefault();
            }
        }

    IUnitOfWork:

    public interface IUnitOfWork : IDisposable
        {
            ICountryRepository CountryRepository();
            IProviceRepository ProvinceRepository();
            ICityRepository CityRepository();
            ITownRepository TownRepository();
            IGroupRepository GroupRepository();
            ICompanyRepository CompanyRepository();
            IDepartmentRepository DepartmentRepository();
            IUserRepository UserRepository();
            IRoleRepository RoleRepository();
            ISubSystemRepository SubSystemRepository();
            IMenuRepository MenuRepository();
            IControllerRepository ControllerRepository();
            IActionRepository ActionRepository();
            ILimitRepository LimitRepository();
            IGroupTypeRepository GroupTypeRepository();
    
            void Save();
        }


    CUnitOfWork:

    public class CUnitOfWork : IUnitOfWork
        {
    
            private static CUnitOfWork unitofwork = null;
    
            public static CUnitOfWork GetInstanse()
            {
                if (unitofwork == null)
                    unitofwork = new CUnitOfWork();
                return unitofwork;
            }
    
            private CUnitOfWork() { }
    
            #region Repositorys
            private CDbContext context = new CDbContext();
    
            private ICountryRepository countryRepository;
            public ICountryRepository CountryRepository()
            {
                //get
                //{
                    if (this.countryRepository == null)
                    {
                        this.countryRepository = new CCountryRepository(context);
                    }
                    return countryRepository;
                //}
            }
    
            private IProviceRepository provinceRepository;
            public IProviceRepository ProvinceRepository()
            {
                //get
                //{
                    if (this.provinceRepository == null)
                    {
                        this.provinceRepository = new CProviceRepository(context);
                    }
                    return provinceRepository;
                //}
            }
    
            private ICityRepository cityRepository;
            public ICityRepository CityRepository()
            {
                //get
                //{
                    if (this.cityRepository == null)
                    {
                        this.cityRepository = new CCityRepository(context);
                    }
                    return cityRepository;
                //}
            }
    
            private ITownRepository townRepository;
            public ITownRepository TownRepository()
            {
                //get
                //{
                    if (this.townRepository == null)
                    {
                        this.townRepository = new CTownRepository(context);
                    }
                    return townRepository;
                //}
            }
    
            private IGroupRepository groupRepository;
            public IGroupRepository GroupRepository()
            {
                //get
                //{
                    if (this.groupRepository == null)
                    {
                        this.groupRepository = new CGroupRepository(context);
                    }
                    return groupRepository;
                //}
            }
    
            private ICompanyRepository companyRepository;
            public ICompanyRepository CompanyRepository()
            {
                //get
                //{
                    if (this.companyRepository == null)
                    {
                        this.companyRepository = new CCompanyRepository(context);
                    }
                    return companyRepository;
                //}
            }
    
            private IDepartmentRepository departmentRepository;
            public IDepartmentRepository DepartmentRepository()
            {
                //get
                //{
                    if (this.departmentRepository == null)
                    {
                        this.departmentRepository = new CDepartmentRepository(context);
                    }
                    return departmentRepository;
                //}
            }
    
            private IUserRepository userRepository;
            public IUserRepository UserRepository()
            {
                //get
                //{
                    if (this.userRepository == null)
                    {
                        this.userRepository = new CUserRepository(context);
                    }
                    return userRepository;
                //}
            }
    
            private IRoleRepository roleRepository;
            public IRoleRepository RoleRepository()
            {
                //get
                //{
                    if (this.roleRepository == null)
                    {
                        this.roleRepository = new CRoleRepository(context);
                    }
                    return roleRepository;
                //}
            }
    
            private ISubSystemRepository subSystemRepository;
            public ISubSystemRepository SubSystemRepository()
            {
                //get
                //{
                    if (this.subSystemRepository == null)
                    {
                        this.subSystemRepository = new CSubSystemRepository(context);
                    }
                    return subSystemRepository;
                //}
            }
    
            private IMenuRepository menuRepository;
            public IMenuRepository MenuRepository()
            {
                //get
                //{
                    if (this.menuRepository == null)
                    {
                        this.menuRepository = new CMenuRepository(context);
                    }
                    return menuRepository;
                //}
            }
    
            private IControllerRepository controllerRepository;
            public IControllerRepository ControllerRepository()
            {
                //get
                //{
                    if (this.controllerRepository == null)
                    {
                        this.controllerRepository = new CControllerRepository(context);
                    }
                    return controllerRepository;
                //}
            }
    
            private IActionRepository actionRepository;
            public IActionRepository ActionRepository()
            {
                //get
                //{
                    if (this.actionRepository == null)
                    {
                        this.actionRepository = new CActionRepository(context);
                    }
                    return actionRepository;
                //}
            }
    
            private ILimitRepository limitRepository;
            public ILimitRepository LimitRepository()
            {
                //get
                //{
                    if (this.limitRepository == null)
                    {
                        this.limitRepository = new CLimitRepository(context);
                    }
                    return limitRepository;
                //}
            }
    
            private IGroupTypeRepository grouptypeRepository;
            public IGroupTypeRepository GroupTypeRepository()
            {
                //get
                //{
                    if (this.grouptypeRepository == null)
                    {
                        this.grouptypeRepository = new CGroupTypeRepository(context);
                    }
                    return grouptypeRepository;
                //}
            }
    
            #endregion
    
            public void Save()
            {
                context.SaveChanges();
            }
    
            private bool disposed = false;
    
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        context.Dispose();
                    }
                }
                this.disposed = true;
            }
    
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

    COperBLL:

    public class COperBLL : CBaseBLL
        {
            private CUser User;
            public CUser GetUserByName(string p_userName)
            {
                if (User == null)
                {
                    User = Unit.UserRepository()
                       .Get(i => i.UserName == p_userName).SingleOrDefault();
                }
                return User;
            }
    
            public void Insert(CUser _user)
            {
                _user.Password = HashPassword(_user.Password);
                Unit.UserRepository().Insert(_user);            
            }
    
            public void Save()
            {
                Unit.Save();
            }
    
            private bool IsOper(string p_userName)
            {
                return GetUserByName(p_userName).IsOper();
            }
    
            public List<CUser> Get(string p_userName)
            {
                if (IsOper(p_userName))
                    return User.GetOperUserList();
                return new List<CUser>();
            }
    
            public CUser Find(int p_id)
            {
                return Unit.UserRepository().GetByID(p_id);
            }
    
            public COperUserAreaList GetOperDepartments(string p_userName)
            {
                if (IsOper(p_userName))
                {
                    return User.GetOperDepartments();
                }
                return new COperUserAreaList();
            }
    
            public bool IsContainUser(string p_userName)
            {
                if (Unit.UserRepository()
                       .Get(i => i.UserName == p_userName).SingleOrDefault() != null)
                    return true;
                return false;
            }
    
            public List<CRole> GetUserUnderRoles(string p_userName)
            {
                if (IsOper(p_userName))
                {
                    return User.GetOperUserRoles(Unit.RoleRepository().Get().ToList());
                }
                return new List<CRole>();
            }
    
            public void SetUserRolesByRolesString(CUser p_User)
            {
                if (p_User == null)
                    return;
                string p_RolesString = p_User.RolesString;
                if (p_RolesString.Length == 0)
                    return;
                string[] arr = p_RolesString.Split(new char[]{'|'}, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in arr)
                {
                    CRole _r = Unit.RoleRepository().GetByName(str);
                    if (_r != null)
                    {
                        p_User.Roles.Add(_r);
                        _r.Users.Add(p_User);
                    }
                }
    
            }
    
            public void Update(CUser p_user)
            {
                Unit.UserRepository().Update(p_user);
            }
        }


     

     

    OperController:

     [Authorize(Roles = "操作员")]
            public ActionResult Edit(int id)
            {
                CUser cuser = operBLL.Find(id);
    
                string Name = User.Identity.Name;
                COperUserAreaList ouas = operBLL.GetOperDepartments(Name);
                ViewBag.ProviceID = new SelectList(ouas.Provinces, "ID", "Name");
                ViewBag.CityID = new SelectList(ouas.Citys, "ID", "Name");
                ViewBag.TownID = new SelectList(ouas.Towns, "ID", "Name");
                ViewBag.GroupID = new SelectList(ouas.Groups, "ID", "Name");
                ViewBag.CompanyID = new SelectList(ouas.Companys, "ID", "Name");
                ViewBag.DepartmentID = new SelectList(ouas.Departments, "ID", "Name");
                ViewBag.RolesID = operBLL.GetUserUnderRoles(Name);
    
                return View(cuser);
            }
    
            [HttpPost]
            public ActionResult Edit(CUser cuser)
            {
                if (ModelState.IsValid)
                {
                    operBLL.Update(cuser);
                    operBLL.Save();
                    return RedirectToAction("Index");
                }
    
                string Name = User.Identity.Name;
                COperUserAreaList ouas = operBLL.GetOperDepartments(Name);
                ViewBag.ProviceID = new SelectList(ouas.Provinces, "ID", "Name");
                ViewBag.CityID = new SelectList(ouas.Citys, "ID", "Name");
                ViewBag.TownID = new SelectList(ouas.Towns, "ID", "Name");
                ViewBag.GroupID = new SelectList(ouas.Groups, "ID", "Name");
                ViewBag.CompanyID = new SelectList(ouas.Companys, "ID", "Name");
                ViewBag.DepartmentID = new SelectList(ouas.Departments, "ID", "Name");
                ViewBag.RolesID = operBLL.GetUserUnderRoles(Name);
                return View(cuser);
            }

    运行后。


    把[HttpPost]里的edit方法里的operBLL.Update(cuser);改为CDbContext context = new CDbContext();

    context.UserSet.Attach(cuser);

    context.Entry(cuser).State = EntityState.Modified

    后不再报错,难道CDbContext不能用单例???请高手赐教!
     

     

    2011年12月6日 2:07

答案

  • 头一回使用EF4.1做项目,在对数据层进行封装后,进行修改时,发现了标题上描述的问题。目标有办法解决,但是有违了数据的封装性。

    上代码:

    CDbContext:

    public class CDbContext : DbContext
        {
            private readonly static string CONNECTION_STRING = "name=CMIIMS_ConnString";
            public CDbContext()
                : base(CONNECTION_STRING)
            {
    
            }
    
            public DbSet<CCountry> CountrySet { get; set; }
            public DbSet<CProvince> ProvinceSet { get; set; }
            public DbSet<CCity> CitySet { get; set; }
            public DbSet<CTown> TownSet { get; set; }
            public DbSet<CGroup> GroupSet { get; set; }
            public DbSet<CCompany> CompanySet { get; set; }
            public DbSet<CDepartment> DepartmentSet { get; set; }
            public DbSet<CUser> UserSet { get; set; }
            public DbSet<CRole> RoleSet { get; set; }
            public DbSet<CSubSystem> SubSystemSet { get; set; }
            public DbSet<CMenu> MenuSet { get; set; }
            public DbSet<CController> ControllerSet { get; set; }
            public DbSet<CAction> ActionSet { get; set; }
            public DbSet<CLimit> LimitSet { get; set; }
            public DbSet<CGroupType> GroupTypeSet { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                //移除复数表名的契约;
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
                ////防止黑幕交易 要不然每次都要访问 EdmMetadata这个表;
                //modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
    
                //modelBuilder.Entity<CUser>().HasOptional(x => x.Department);
                //modelBuilder.Entity<CDepartment>().HasOptional(x => x.Company);
                //modelBuilder.Entity<CCompany>().HasOptional(x => x.Group);
                //modelBuilder.Entity<CGroup>().HasOptional(x => x.Town);
                //modelBuilder.Entity<CTown>().HasOptional(x => x.City);
                //modelBuilder.Entity<CCity>().HasOptional(x => x.Province);
    
                modelBuilder.Entity<CRole>().HasMany(c => c.Users).WithMany(i => i.Roles)
                    .Map(t => t.MapLeftKey("UserID").MapRightKey("RoleID").ToTable("TXTS_UserRole"));
    
                modelBuilder.Entity<CAction>().HasMany(c => c.Limits).WithMany(i => i.Actions)
                    .Map(t => t.MapLeftKey("ActionID").MapRightKey("LimitID").ToTable("TXTS_ActionLimit"));
    
                modelBuilder.Entity<CController>().HasMany(c => c.Limits).WithMany(i => i.Controllers)
                    .Map(t => t.MapLeftKey("ControllerID").MapRightKey("LimitID").ToTable("TXTS_ControllerLimit"));
    
                modelBuilder.Entity<CSubSystem>().HasMany(c => c.Limits).WithMany(i => i.SubSystems)
                    .Map(t => t.MapLeftKey("SubSystemID").MapRightKey("LimitID").ToTable("TXTS_SubSystemLimit"));
    
                modelBuilder.Entity<CMenu>().HasMany(c => c.Limits).WithMany(i => i.Menus)
                    .Map(t => t.MapLeftKey("MenuID").MapRightKey("LimitID").ToTable("TXTS_MenuLimit"));
            }
    
    
    

     

    IGenericRpository接口

    public interface IGenericRepository<TEntity> where TEntity : CBase
        {
            IEnumerable<TEntity> Get(
                Expression<Func<TEntity, bool>> filter = null,
                Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                string includeProperties = "");
    
            TEntity GetByID(object id);
    
            void Insert(TEntity entity);
    
            void Delete(object id);
    
            void Delete(TEntity entityToDelete);
    
           <strong> void Update(TEntity entityToUpdate);
    
    </strong>        IEnumerable<TEntity> GetWithRawSql(
                string query, params object[] parameters);
    
            int ExecSql(
                string strsqlCom, params object[] parameters);
        }
    
    
    

    CGenericRepository

    public class CGenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : CBase
        {
            public CDbContext context;
            public DbSet<TEntity> dbSet;
    
            public CGenericRepository(CDbContext context)
            {
                this.context = context;
                this.dbSet = context.Set<TEntity>();
            }
    
            public virtual IEnumerable<TEntity> Get(
                Expression<Func<TEntity, bool>> filter = null,
                Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                string includeProperties = "")
            {
                IQueryable<TEntity> query = dbSet;
    
                if (filter != null)
                {
                    query = query.Where(filter).Where(i => !i.IsDeleted);
                }
    
                foreach (var includeProperty in includeProperties.Split
                    (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    query = query.Include(includeProperty);
                }
    
                if (orderBy != null)
                {
                    return orderBy(query).ToList();
                }
                else
                {
                    return query.ToList();
                }
            }
    
            public virtual TEntity GetByID(object id)
            {
                return dbSet.Find(id);
            }
    
            public virtual void Insert(TEntity entity)
            {
                dbSet.Add(entity);
            }
    
            public virtual void Delete(object id)
            {
                TEntity entityToDelete = dbSet.Find(id);
                Delete(entityToDelete);
            }
    
            public virtual void Delete(TEntity entityToDelete)
            {
                if (context.Entry(entityToDelete).State == EntityState.Detached)
                {
                    dbSet.Attach(entityToDelete);
                }
                //dbSet.Remove(entityToDelete);
                entityToDelete.IsDeleted = true;
                Update(entityToDelete);
            }
    
            public virtual void Update(TEntity entityToUpdate)
            {
                dbSet.Attach(entityToUpdate);
                context.Entry(entityToUpdate).State = EntityState.Modified;
            }
    
            public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
            {
                return dbSet.SqlQuery(query, parameters).ToList();
            }
    
            public virtual int ExecSql(string strsqlCom, params object[] parameters)
            {
                return -1;
            }

    IUserRepository:

    public interface IUserRepository : IGenericRepository<CUser>
        {
            CUser ValidateLogon(string UserName, string hashed_pw);
        }
    
    

    CUserRepository:

    public class CUserRepository : CGenericRepository<CUser>, IUserRepository
        {
            public CUserRepository(CDbContext context) : base(context) { }
    
            public CUser ValidateLogon(string UserName, string hashed_pw)
            {
                return Get(i => i.UserName == UserName && i.Password == hashed_pw)
                    .FirstOrDefault();
            }
        }

    IUnitOfWork:

    public interface IUnitOfWork : IDisposable
        {
            ICountryRepository CountryRepository();
            IProviceRepository ProvinceRepository();
            ICityRepository CityRepository();
            ITownRepository TownRepository();
            IGroupRepository GroupRepository();
            ICompanyRepository CompanyRepository();
            IDepartmentRepository DepartmentRepository();
            IUserRepository UserRepository();
            IRoleRepository RoleRepository();
            ISubSystemRepository SubSystemRepository();
            IMenuRepository MenuRepository();
            IControllerRepository ControllerRepository();
            IActionRepository ActionRepository();
            ILimitRepository LimitRepository();
            IGroupTypeRepository GroupTypeRepository();
    
            void Save();
        }


    CUnitOfWork:

    public class CUnitOfWork : IUnitOfWork
        {
    
            private static CUnitOfWork unitofwork = null;
    
            public static CUnitOfWork GetInstanse()
            {
                if (unitofwork == null)
                    unitofwork = new CUnitOfWork();
                return unitofwork;
            }
    
            private CUnitOfWork() { }
    
            #region Repositorys
            private CDbContext context = new CDbContext();
    
            private ICountryRepository countryRepository;
            public ICountryRepository CountryRepository()
            {
                //get
                //{
                    if (this.countryRepository == null)
                    {
                        this.countryRepository = new CCountryRepository(context);
                    }
                    return countryRepository;
                //}
            }
    
            private IProviceRepository provinceRepository;
            public IProviceRepository ProvinceRepository()
            {
                //get
                //{
                    if (this.provinceRepository == null)
                    {
                        this.provinceRepository = new CProviceRepository(context);
                    }
                    return provinceRepository;
                //}
            }
    
            private ICityRepository cityRepository;
            public ICityRepository CityRepository()
            {
                //get
                //{
                    if (this.cityRepository == null)
                    {
                        this.cityRepository = new CCityRepository(context);
                    }
                    return cityRepository;
                //}
            }
    
            private ITownRepository townRepository;
            public ITownRepository TownRepository()
            {
                //get
                //{
                    if (this.townRepository == null)
                    {
                        this.townRepository = new CTownRepository(context);
                    }
                    return townRepository;
                //}
            }
    
            private IGroupRepository groupRepository;
            public IGroupRepository GroupRepository()
            {
                //get
                //{
                    if (this.groupRepository == null)
                    {
                        this.groupRepository = new CGroupRepository(context);
                    }
                    return groupRepository;
                //}
            }
    
            private ICompanyRepository companyRepository;
            public ICompanyRepository CompanyRepository()
            {
                //get
                //{
                    if (this.companyRepository == null)
                    {
                        this.companyRepository = new CCompanyRepository(context);
                    }
                    return companyRepository;
                //}
            }
    
            private IDepartmentRepository departmentRepository;
            public IDepartmentRepository DepartmentRepository()
            {
                //get
                //{
                    if (this.departmentRepository == null)
                    {
                        this.departmentRepository = new CDepartmentRepository(context);
                    }
                    return departmentRepository;
                //}
            }
    
            private IUserRepository userRepository;
            public IUserRepository UserRepository()
            {
                //get
                //{
                    if (this.userRepository == null)
                    {
                        this.userRepository = new CUserRepository(context);
                    }
                    return userRepository;
                //}
            }
    
            private IRoleRepository roleRepository;
            public IRoleRepository RoleRepository()
            {
                //get
                //{
                    if (this.roleRepository == null)
                    {
                        this.roleRepository = new CRoleRepository(context);
                    }
                    return roleRepository;
                //}
            }
    
            private ISubSystemRepository subSystemRepository;
            public ISubSystemRepository SubSystemRepository()
            {
                //get
                //{
                    if (this.subSystemRepository == null)
                    {
                        this.subSystemRepository = new CSubSystemRepository(context);
                    }
                    return subSystemRepository;
                //}
            }
    
            private IMenuRepository menuRepository;
            public IMenuRepository MenuRepository()
            {
                //get
                //{
                    if (this.menuRepository == null)
                    {
                        this.menuRepository = new CMenuRepository(context);
                    }
                    return menuRepository;
                //}
            }
    
            private IControllerRepository controllerRepository;
            public IControllerRepository ControllerRepository()
            {
                //get
                //{
                    if (this.controllerRepository == null)
                    {
                        this.controllerRepository = new CControllerRepository(context);
                    }
                    return controllerRepository;
                //}
            }
    
            private IActionRepository actionRepository;
            public IActionRepository ActionRepository()
            {
                //get
                //{
                    if (this.actionRepository == null)
                    {
                        this.actionRepository = new CActionRepository(context);
                    }
                    return actionRepository;
                //}
            }
    
            private ILimitRepository limitRepository;
            public ILimitRepository LimitRepository()
            {
                //get
                //{
                    if (this.limitRepository == null)
                    {
                        this.limitRepository = new CLimitRepository(context);
                    }
                    return limitRepository;
                //}
            }
    
            private IGroupTypeRepository grouptypeRepository;
            public IGroupTypeRepository GroupTypeRepository()
            {
                //get
                //{
                    if (this.grouptypeRepository == null)
                    {
                        this.grouptypeRepository = new CGroupTypeRepository(context);
                    }
                    return grouptypeRepository;
                //}
            }
    
            #endregion
    
            public void Save()
            {
                context.SaveChanges();
            }
    
            private bool disposed = false;
    
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        context.Dispose();
                    }
                }
                this.disposed = true;
            }
    
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

    COperBLL:

    public class COperBLL : CBaseBLL
        {
            private CUser User;
            public CUser GetUserByName(string p_userName)
            {
                if (User == null)
                {
                    User = Unit.UserRepository()
                       .Get(i => i.UserName == p_userName).SingleOrDefault();
                }
                return User;
            }
    
            public void Insert(CUser _user)
            {
                _user.Password = HashPassword(_user.Password);
                Unit.UserRepository().Insert(_user);            
            }
    
            public void Save()
            {
                Unit.Save();
            }
    
            private bool IsOper(string p_userName)
            {
                return GetUserByName(p_userName).IsOper();
            }
    
            public List<CUser> Get(string p_userName)
            {
                if (IsOper(p_userName))
                    return User.GetOperUserList();
                return new List<CUser>();
            }
    
            public CUser Find(int p_id)
            {
                return Unit.UserRepository().GetByID(p_id);
            }
    
            public COperUserAreaList GetOperDepartments(string p_userName)
            {
                if (IsOper(p_userName))
                {
                    return User.GetOperDepartments();
                }
                return new COperUserAreaList();
            }
    
            public bool IsContainUser(string p_userName)
            {
                if (Unit.UserRepository()
                       .Get(i => i.UserName == p_userName).SingleOrDefault() != null)
                    return true;
                return false;
            }
    
            public List<CRole> GetUserUnderRoles(string p_userName)
            {
                if (IsOper(p_userName))
                {
                    return User.GetOperUserRoles(Unit.RoleRepository().Get().ToList());
                }
                return new List<CRole>();
            }
    
            public void SetUserRolesByRolesString(CUser p_User)
            {
                if (p_User == null)
                    return;
                string p_RolesString = p_User.RolesString;
                if (p_RolesString.Length == 0)
                    return;
                string[] arr = p_RolesString.Split(new char[]{'|'}, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in arr)
                {
                    CRole _r = Unit.RoleRepository().GetByName(str);
                    if (_r != null)
                    {
                        p_User.Roles.Add(_r);
                        _r.Users.Add(p_User);
                    }
                }
    
            }
    
            public void Update(CUser p_user)
            {
                Unit.UserRepository().Update(p_user);
            }
        }

     

     

    OperController:

     [Authorize(Roles = "操作员")]
            public ActionResult Edit(int id)
            {
                CUser cuser = operBLL.Find(id);
    
                string Name = User.Identity.Name;
                COperUserAreaList ouas = operBLL.GetOperDepartments(Name);
                ViewBag.ProviceID = new SelectList(ouas.Provinces, "ID", "Name");
                ViewBag.CityID = new SelectList(ouas.Citys, "ID", "Name");
                ViewBag.TownID = new SelectList(ouas.Towns, "ID", "Name");
                ViewBag.GroupID = new SelectList(ouas.Groups, "ID", "Name");
                ViewBag.CompanyID = new SelectList(ouas.Companys, "ID", "Name");
                ViewBag.DepartmentID = new SelectList(ouas.Departments, "ID", "Name");
                ViewBag.RolesID = operBLL.GetUserUnderRoles(Name);
    
                return View(cuser);
            }
    
            [HttpPost]
            public ActionResult Edit(CUser cuser)
            {
                if (ModelState.IsValid)
                {
                    operBLL.Update(cuser);
                    operBLL.Save();
                    return RedirectToAction("Index");
                }
    
                string Name = User.Identity.Name;
                COperUserAreaList ouas = operBLL.GetOperDepartments(Name);
                ViewBag.ProviceID = new SelectList(ouas.Provinces, "ID", "Name");
                ViewBag.CityID = new SelectList(ouas.Citys, "ID", "Name");
                ViewBag.TownID = new SelectList(ouas.Towns, "ID", "Name");
                ViewBag.GroupID = new SelectList(ouas.Groups, "ID", "Name");
                ViewBag.CompanyID = new SelectList(ouas.Companys, "ID", "Name");
                ViewBag.DepartmentID = new SelectList(ouas.Departments, "ID", "Name");
                ViewBag.RolesID = operBLL.GetUserUnderRoles(Name);
                return View(cuser);
            }

    运行后。


    把[HttpPost]里的edit方法里的operBLL.Update(cuser);改为CDbContext context = new CDbContext();

    context.UserSet.Attach(cuser);

    context.Entry(cuser).State = EntityState.Modified

    后不再报错,难道CDbContext不能用单例???请高手赐教!

     


    public virtual void Update(TEntity entityToUpdate)
            {
                using(CDbContext context = new CDbContext())
                {
                    context.Set<TEntity>().Attach(entityToUpdate);
                    context.Entry(entityToUpdate).State = EntityState.Modified;
                    context.SaveChanges();
                }
            }

    建议每次用using块解决问题,而不是用一个context,这样容易引发问题。


       QQ我:讨论(Talk)
    下载MSDN桌面工具(Vista,Win7)
    我的博客园
    慈善点击,点击此处
    • 已标记为答案 殷学松 2011年12月6日 2:57
    2011年12月6日 2:56

全部回复

  • 头一回使用EF4.1做项目,在对数据层进行封装后,进行修改时,发现了标题上描述的问题。目标有办法解决,但是有违了数据的封装性。

    上代码:

    CDbContext:

    public class CDbContext : DbContext
        {
            private readonly static string CONNECTION_STRING = "name=CMIIMS_ConnString";
            public CDbContext()
                : base(CONNECTION_STRING)
            {
    
            }
    
            public DbSet<CCountry> CountrySet { get; set; }
            public DbSet<CProvince> ProvinceSet { get; set; }
            public DbSet<CCity> CitySet { get; set; }
            public DbSet<CTown> TownSet { get; set; }
            public DbSet<CGroup> GroupSet { get; set; }
            public DbSet<CCompany> CompanySet { get; set; }
            public DbSet<CDepartment> DepartmentSet { get; set; }
            public DbSet<CUser> UserSet { get; set; }
            public DbSet<CRole> RoleSet { get; set; }
            public DbSet<CSubSystem> SubSystemSet { get; set; }
            public DbSet<CMenu> MenuSet { get; set; }
            public DbSet<CController> ControllerSet { get; set; }
            public DbSet<CAction> ActionSet { get; set; }
            public DbSet<CLimit> LimitSet { get; set; }
            public DbSet<CGroupType> GroupTypeSet { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                //移除复数表名的契约;
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
                ////防止黑幕交易 要不然每次都要访问 EdmMetadata这个表;
                //modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
    
                //modelBuilder.Entity<CUser>().HasOptional(x => x.Department);
                //modelBuilder.Entity<CDepartment>().HasOptional(x => x.Company);
                //modelBuilder.Entity<CCompany>().HasOptional(x => x.Group);
                //modelBuilder.Entity<CGroup>().HasOptional(x => x.Town);
                //modelBuilder.Entity<CTown>().HasOptional(x => x.City);
                //modelBuilder.Entity<CCity>().HasOptional(x => x.Province);
    
                modelBuilder.Entity<CRole>().HasMany(c => c.Users).WithMany(i => i.Roles)
                    .Map(t => t.MapLeftKey("UserID").MapRightKey("RoleID").ToTable("TXTS_UserRole"));
    
                modelBuilder.Entity<CAction>().HasMany(c => c.Limits).WithMany(i => i.Actions)
                    .Map(t => t.MapLeftKey("ActionID").MapRightKey("LimitID").ToTable("TXTS_ActionLimit"));
    
                modelBuilder.Entity<CController>().HasMany(c => c.Limits).WithMany(i => i.Controllers)
                    .Map(t => t.MapLeftKey("ControllerID").MapRightKey("LimitID").ToTable("TXTS_ControllerLimit"));
    
                modelBuilder.Entity<CSubSystem>().HasMany(c => c.Limits).WithMany(i => i.SubSystems)
                    .Map(t => t.MapLeftKey("SubSystemID").MapRightKey("LimitID").ToTable("TXTS_SubSystemLimit"));
    
                modelBuilder.Entity<CMenu>().HasMany(c => c.Limits).WithMany(i => i.Menus)
                    .Map(t => t.MapLeftKey("MenuID").MapRightKey("LimitID").ToTable("TXTS_MenuLimit"));
            }
    
    
    

     

    IGenericRpository接口

    public interface IGenericRepository<TEntity> where TEntity : CBase
        {
            IEnumerable<TEntity> Get(
                Expression<Func<TEntity, bool>> filter = null,
                Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                string includeProperties = "");
    
            TEntity GetByID(object id);
    
            void Insert(TEntity entity);
    
            void Delete(object id);
    
            void Delete(TEntity entityToDelete);
    
           <strong> void Update(TEntity entityToUpdate);
    
    </strong>        IEnumerable<TEntity> GetWithRawSql(
                string query, params object[] parameters);
    
            int ExecSql(
                string strsqlCom, params object[] parameters);
        }
    
    
    

    CGenericRepository

    public class CGenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : CBase
        {
            public CDbContext context;
            public DbSet<TEntity> dbSet;
    
            public CGenericRepository(CDbContext context)
            {
                this.context = context;
                this.dbSet = context.Set<TEntity>();
            }
    
            public virtual IEnumerable<TEntity> Get(
                Expression<Func<TEntity, bool>> filter = null,
                Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
                string includeProperties = "")
            {
                IQueryable<TEntity> query = dbSet;
    
                if (filter != null)
                {
                    query = query.Where(filter).Where(i => !i.IsDeleted);
                }
    
                foreach (var includeProperty in includeProperties.Split
                    (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    query = query.Include(includeProperty);
                }
    
                if (orderBy != null)
                {
                    return orderBy(query).ToList();
                }
                else
                {
                    return query.ToList();
                }
            }
    
            public virtual TEntity GetByID(object id)
            {
                return dbSet.Find(id);
            }
    
            public virtual void Insert(TEntity entity)
            {
                dbSet.Add(entity);
            }
    
            public virtual void Delete(object id)
            {
                TEntity entityToDelete = dbSet.Find(id);
                Delete(entityToDelete);
            }
    
            public virtual void Delete(TEntity entityToDelete)
            {
                if (context.Entry(entityToDelete).State == EntityState.Detached)
                {
                    dbSet.Attach(entityToDelete);
                }
                //dbSet.Remove(entityToDelete);
                entityToDelete.IsDeleted = true;
                Update(entityToDelete);
            }
    
            public virtual void Update(TEntity entityToUpdate)
            {
                dbSet.Attach(entityToUpdate);
                context.Entry(entityToUpdate).State = EntityState.Modified;
            }
    
            public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
            {
                return dbSet.SqlQuery(query, parameters).ToList();
            }
    
            public virtual int ExecSql(string strsqlCom, params object[] parameters)
            {
                return -1;
            }

    IUserRepository:

    public interface IUserRepository : IGenericRepository<CUser>
        {
            CUser ValidateLogon(string UserName, string hashed_pw);
        }
    
    

    CUserRepository:

    public class CUserRepository : CGenericRepository<CUser>, IUserRepository
        {
            public CUserRepository(CDbContext context) : base(context) { }
    
            public CUser ValidateLogon(string UserName, string hashed_pw)
            {
                return Get(i => i.UserName == UserName && i.Password == hashed_pw)
                    .FirstOrDefault();
            }
        }

    IUnitOfWork:

    public interface IUnitOfWork : IDisposable
        {
            ICountryRepository CountryRepository();
            IProviceRepository ProvinceRepository();
            ICityRepository CityRepository();
            ITownRepository TownRepository();
            IGroupRepository GroupRepository();
            ICompanyRepository CompanyRepository();
            IDepartmentRepository DepartmentRepository();
            IUserRepository UserRepository();
            IRoleRepository RoleRepository();
            ISubSystemRepository SubSystemRepository();
            IMenuRepository MenuRepository();
            IControllerRepository ControllerRepository();
            IActionRepository ActionRepository();
            ILimitRepository LimitRepository();
            IGroupTypeRepository GroupTypeRepository();
    
            void Save();
        }


    CUnitOfWork:

    public class CUnitOfWork : IUnitOfWork
        {
    
            private static CUnitOfWork unitofwork = null;
    
            public static CUnitOfWork GetInstanse()
            {
                if (unitofwork == null)
                    unitofwork = new CUnitOfWork();
                return unitofwork;
            }
    
            private CUnitOfWork() { }
    
            #region Repositorys
            private CDbContext context = new CDbContext();
    
            private ICountryRepository countryRepository;
            public ICountryRepository CountryRepository()
            {
                //get
                //{
                    if (this.countryRepository == null)
                    {
                        this.countryRepository = new CCountryRepository(context);
                    }
                    return countryRepository;
                //}
            }
    
            private IProviceRepository provinceRepository;
            public IProviceRepository ProvinceRepository()
            {
                //get
                //{
                    if (this.provinceRepository == null)
                    {
                        this.provinceRepository = new CProviceRepository(context);
                    }
                    return provinceRepository;
                //}
            }
    
            private ICityRepository cityRepository;
            public ICityRepository CityRepository()
            {
                //get
                //{
                    if (this.cityRepository == null)
                    {
                        this.cityRepository = new CCityRepository(context);
                    }
                    return cityRepository;
                //}
            }
    
            private ITownRepository townRepository;
            public ITownRepository TownRepository()
            {
                //get
                //{
                    if (this.townRepository == null)
                    {
                        this.townRepository = new CTownRepository(context);
                    }
                    return townRepository;
                //}
            }
    
            private IGroupRepository groupRepository;
            public IGroupRepository GroupRepository()
            {
                //get
                //{
                    if (this.groupRepository == null)
                    {
                        this.groupRepository = new CGroupRepository(context);
                    }
                    return groupRepository;
                //}
            }
    
            private ICompanyRepository companyRepository;
            public ICompanyRepository CompanyRepository()
            {
                //get
                //{
                    if (this.companyRepository == null)
                    {
                        this.companyRepository = new CCompanyRepository(context);
                    }
                    return companyRepository;
                //}
            }
    
            private IDepartmentRepository departmentRepository;
            public IDepartmentRepository DepartmentRepository()
            {
                //get
                //{
                    if (this.departmentRepository == null)
                    {
                        this.departmentRepository = new CDepartmentRepository(context);
                    }
                    return departmentRepository;
                //}
            }
    
            private IUserRepository userRepository;
            public IUserRepository UserRepository()
            {
                //get
                //{
                    if (this.userRepository == null)
                    {
                        this.userRepository = new CUserRepository(context);
                    }
                    return userRepository;
                //}
            }
    
            private IRoleRepository roleRepository;
            public IRoleRepository RoleRepository()
            {
                //get
                //{
                    if (this.roleRepository == null)
                    {
                        this.roleRepository = new CRoleRepository(context);
                    }
                    return roleRepository;
                //}
            }
    
            private ISubSystemRepository subSystemRepository;
            public ISubSystemRepository SubSystemRepository()
            {
                //get
                //{
                    if (this.subSystemRepository == null)
                    {
                        this.subSystemRepository = new CSubSystemRepository(context);
                    }
                    return subSystemRepository;
                //}
            }
    
            private IMenuRepository menuRepository;
            public IMenuRepository MenuRepository()
            {
                //get
                //{
                    if (this.menuRepository == null)
                    {
                        this.menuRepository = new CMenuRepository(context);
                    }
                    return menuRepository;
                //}
            }
    
            private IControllerRepository controllerRepository;
            public IControllerRepository ControllerRepository()
            {
                //get
                //{
                    if (this.controllerRepository == null)
                    {
                        this.controllerRepository = new CControllerRepository(context);
                    }
                    return controllerRepository;
                //}
            }
    
            private IActionRepository actionRepository;
            public IActionRepository ActionRepository()
            {
                //get
                //{
                    if (this.actionRepository == null)
                    {
                        this.actionRepository = new CActionRepository(context);
                    }
                    return actionRepository;
                //}
            }
    
            private ILimitRepository limitRepository;
            public ILimitRepository LimitRepository()
            {
                //get
                //{
                    if (this.limitRepository == null)
                    {
                        this.limitRepository = new CLimitRepository(context);
                    }
                    return limitRepository;
                //}
            }
    
            private IGroupTypeRepository grouptypeRepository;
            public IGroupTypeRepository GroupTypeRepository()
            {
                //get
                //{
                    if (this.grouptypeRepository == null)
                    {
                        this.grouptypeRepository = new CGroupTypeRepository(context);
                    }
                    return grouptypeRepository;
                //}
            }
    
            #endregion
    
            public void Save()
            {
                context.SaveChanges();
            }
    
            private bool disposed = false;
    
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        context.Dispose();
                    }
                }
                this.disposed = true;
            }
    
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
        }

    COperBLL:

    public class COperBLL : CBaseBLL
        {
            private CUser User;
            public CUser GetUserByName(string p_userName)
            {
                if (User == null)
                {
                    User = Unit.UserRepository()
                       .Get(i => i.UserName == p_userName).SingleOrDefault();
                }
                return User;
            }
    
            public void Insert(CUser _user)
            {
                _user.Password = HashPassword(_user.Password);
                Unit.UserRepository().Insert(_user);            
            }
    
            public void Save()
            {
                Unit.Save();
            }
    
            private bool IsOper(string p_userName)
            {
                return GetUserByName(p_userName).IsOper();
            }
    
            public List<CUser> Get(string p_userName)
            {
                if (IsOper(p_userName))
                    return User.GetOperUserList();
                return new List<CUser>();
            }
    
            public CUser Find(int p_id)
            {
                return Unit.UserRepository().GetByID(p_id);
            }
    
            public COperUserAreaList GetOperDepartments(string p_userName)
            {
                if (IsOper(p_userName))
                {
                    return User.GetOperDepartments();
                }
                return new COperUserAreaList();
            }
    
            public bool IsContainUser(string p_userName)
            {
                if (Unit.UserRepository()
                       .Get(i => i.UserName == p_userName).SingleOrDefault() != null)
                    return true;
                return false;
            }
    
            public List<CRole> GetUserUnderRoles(string p_userName)
            {
                if (IsOper(p_userName))
                {
                    return User.GetOperUserRoles(Unit.RoleRepository().Get().ToList());
                }
                return new List<CRole>();
            }
    
            public void SetUserRolesByRolesString(CUser p_User)
            {
                if (p_User == null)
                    return;
                string p_RolesString = p_User.RolesString;
                if (p_RolesString.Length == 0)
                    return;
                string[] arr = p_RolesString.Split(new char[]{'|'}, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in arr)
                {
                    CRole _r = Unit.RoleRepository().GetByName(str);
                    if (_r != null)
                    {
                        p_User.Roles.Add(_r);
                        _r.Users.Add(p_User);
                    }
                }
    
            }
    
            public void Update(CUser p_user)
            {
                Unit.UserRepository().Update(p_user);
            }
        }

     

     

    OperController:

     [Authorize(Roles = "操作员")]
            public ActionResult Edit(int id)
            {
                CUser cuser = operBLL.Find(id);
    
                string Name = User.Identity.Name;
                COperUserAreaList ouas = operBLL.GetOperDepartments(Name);
                ViewBag.ProviceID = new SelectList(ouas.Provinces, "ID", "Name");
                ViewBag.CityID = new SelectList(ouas.Citys, "ID", "Name");
                ViewBag.TownID = new SelectList(ouas.Towns, "ID", "Name");
                ViewBag.GroupID = new SelectList(ouas.Groups, "ID", "Name");
                ViewBag.CompanyID = new SelectList(ouas.Companys, "ID", "Name");
                ViewBag.DepartmentID = new SelectList(ouas.Departments, "ID", "Name");
                ViewBag.RolesID = operBLL.GetUserUnderRoles(Name);
    
                return View(cuser);
            }
    
            [HttpPost]
            public ActionResult Edit(CUser cuser)
            {
                if (ModelState.IsValid)
                {
                    operBLL.Update(cuser);
                    operBLL.Save();
                    return RedirectToAction("Index");
                }
    
                string Name = User.Identity.Name;
                COperUserAreaList ouas = operBLL.GetOperDepartments(Name);
                ViewBag.ProviceID = new SelectList(ouas.Provinces, "ID", "Name");
                ViewBag.CityID = new SelectList(ouas.Citys, "ID", "Name");
                ViewBag.TownID = new SelectList(ouas.Towns, "ID", "Name");
                ViewBag.GroupID = new SelectList(ouas.Groups, "ID", "Name");
                ViewBag.CompanyID = new SelectList(ouas.Companys, "ID", "Name");
                ViewBag.DepartmentID = new SelectList(ouas.Departments, "ID", "Name");
                ViewBag.RolesID = operBLL.GetUserUnderRoles(Name);
                return View(cuser);
            }

    运行后。


    把[HttpPost]里的edit方法里的operBLL.Update(cuser);改为CDbContext context = new CDbContext();

    context.UserSet.Attach(cuser);

    context.Entry(cuser).State = EntityState.Modified

    后不再报错,难道CDbContext不能用单例???请高手赐教!

     


    public virtual void Update(TEntity entityToUpdate)
            {
                using(CDbContext context = new CDbContext())
                {
                    context.Set<TEntity>().Attach(entityToUpdate);
                    context.Entry(entityToUpdate).State = EntityState.Modified;
                    context.SaveChanges();
                }
            }

    建议每次用using块解决问题,而不是用一个context,这样容易引发问题。


       QQ我:讨论(Talk)
    下载MSDN桌面工具(Vista,Win7)
    我的博客园
    慈善点击,点击此处
    • 已标记为答案 殷学松 2011年12月6日 2:57
    2011年12月6日 2:56
  • 谢谢您的远程。学习到很多。
    2011年12月6日 2:57
  • 您好,

    很高兴您的问题已经得到解决,如果有什么问题,可随时来论坛里提问。


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us
    2011年12月8日 1:42
    版主