EntityFramework SaveChanges在出错后停止工作

时间:2013-06-26 18:03:51

标签: asp.net entity-framework

我正在使用Microsoft Contoso大学示例中使用的通用存储库/工作单元代码:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

它工作正常(它保存,检索,更新,删除等),直到数据库级别出现错误。特别是,我尝试插入一个插入,其中一个字段对于传递给它的文本来说太短。当然失败了。错误被捕获在try / catch块中,然后显示错误消息。问题是,在此之后,即使向表单输入新信息(这是有效的,如同正确的文本大小),SaveChanges方法仍然失败,具有完全相同的错误(字段XYZ必须是字符串或数组类型最大长度为'999')。它只会在我停止调试并重新启动ASP.NET项目

的执行之前停止

为清楚起见,这是我的代码: (GenericRepository.cs)

public class GenericRepository<TEntity> where TEntity : class
{
    internal DBORAContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(DBORAContext 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);
        }

        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);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }                
}

(UnitOfWork.cs)

public class UnitOfWork : IDisposable 
    {
        private DBORAContext context = new DBORAContext();        
        private GenericRepository<Activity> activityRepository;        
        public GenericRepository<Activity> ActivityRepository
        {
            get
            {

                if (this.activityRepository == null)
                {
                    this.activityRepository = new GenericRepository<Activity>(context);
                }
                return activityRepository;
            }
        }        

        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);
        } 
    }

这是调用此特定对象(Activity.cs)的存储库的类

public class Activity
    {
        private static readonly UnitOfWork unitOfWork = new UnitOfWork();                

        public static POCO.Activity Get(Guid activityId)
        {
            try
            {
                var thisActivity = unitOfWork.ActivityRepository.Get(a => a.ACTIVITYID == activityId).FirstOrDefault();

                if (null != thisActivity)
                {
                    return thisActivity;
                }
                return null;
            }
            catch (Exception ex)
            {                
                new Logger(ex.Message);
                return null;
            }            
        }

        public static POCO.Activity Add(POCO.Activity activityToInsert)
        {
            try
            {
                unitOfWork.ActivityRepository.Insert(activityToInsert);
                unitOfWork.Save();
                return activityToInsert;
            }            
            catch (Exception ex)
            {
                //log.Error("Add activity error", ex);
                new Logger(ex.Message);
                throw;
            }
        }

        public static bool Update(POCO.Activity activityToUpdate)
        {
            try
            {
                unitOfWork.ActivityRepository.Update(activityToUpdate);
                unitOfWork.Save();
                return true;
            }            
            catch (Exception ex)
            {
                //log.Error("update activity error", ex);
                new Logger(ex.Message);
                throw;
            }
        }     

        public static bool Delete(POCO.Activity activityToDelete)
        {
            try
            {
                unitOfWork.ActivityRepository.Delete(activityToDelete);
                unitOfWork.Save();
                return true;
            }            
            catch (Exception ex)
            {                
                new Logger(ex.Message);
                throw;
            }
        }
    }

我在Oracle数据库上使用EF 4.3。请帮忙。

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,这对我有用:

我从以下行中删除了关键字static
private static readonly UnitOfWork unitOfWork = new UnitOfWork();

使用static时,应用程序在其整个生命周期中都会保留相同的对象,这就是即使在以表格形式输入新信息后仍保留初始错误的原因。

答案 1 :(得分:0)

问题是你的工作单位是单身人士。工作单位需要较小的范围。如果这是一个Web应用程序,那么http上下文是一个很好的对象来定义UoW。

request.begin - &gt;开始UoW request.end - &gt;完成UoW

如果这是一项服务,那么每项服务请求都可以开始/结束Uow。

如果这是一个富客户端,则可以覆盖每个UI表单。