简体   繁体   English

如何解决 System.Data.Entity.Core.OptimisticConcurrencyException 的这个错误

[英]How to solve this error of System.Data.Entity.Core.OptimisticConcurrencyException

Exception type :异常类型:

System.DataEntity.Core.OptimisticConcurrencyException System.DataEntity.Core.OptimisticConcurrencyException

Message :信息 :

Store update, insert, or delete statement affected an unexpected number of rows (0).存储更新、插入或删除语句影响了意外的行数 (0)。 Entities may have been modified or deleted since entities were loaded.自加载实体以来,实体可能已被修改或删除。 Refresh ObjectStateManager entries.刷新 ObjectStateManager 条目。

Stack trace:堆栈跟踪:

System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRow>sAffected(Int64, System.Data.Entity.Core.Mapping.Update.Internal.UpdateCommand) System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRow>sAffected(Int64, System.Data.Entity.Core.Mapping.Update.Internal.UpdateCommand)
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[[System.Int32, mscorlib]](System.Func1, System.Data.Entity.Infrastructure.IDbExecutionStrategy, Boolean, Boolean) System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[[System.Int32, mscorlib]](System.Func1, System.Data. Entity.Infrastructure.IDbExecutionStrategy, Boolean, Boolean)
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(System.Data.Entity.Core.Objects.SaveOptions, System.Data.Entity.Infrastructure.IDbExecutionStrategy, Boolean) System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(System.Data.Entity.Core.Objects.SaveOptions, System.Data.Entity.Infrastructure.IDbExecutionStrategy, Boolean)
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[System.Int32, mscorlib] System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[System.Int32, mscorlib]
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(System.Data.Entity.Core.Objects.SaveOptions, Boolean) System.Data.Entity.Internal.InternalContext.SaveChanges() System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(System.Data.Entity.Core.Objects.SaveOptions, Boolean) System.Data.Entity.Internal.InternalContext.SaveChanges()

Code 1) EfRepository:代码 1) EfRepository:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using Nop.Core;
using Nop.Core.Data;
namespace Nop.Data
{
    /// <summary>
    /// Entity Framework repository
    /// </summary>
    public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        #region Fields
        private readonly IDbContext _context;
        private IDbSet<T> _entities;
        #endregion
        #region Ctor
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="context">Object context</param>
        public EfRepository(IDbContext context)
        {
            this._context = context;
        }

        #endregion 
        #region Methods
        /// <summary>
        /// Get entity by identifier
        /// </summary>
        /// <param name="id">Identifier</param>
        /// <returns>Entity</returns>
        public virtual T GetById(object id)
        {
            //see some suggested performance optimization (not tested)
            //http://stackoverflow.com/questions/11686225/dbset-find-method-ridiculously-slow-compared-to-singleordefault-on-id/11688189#comment34876113_11688189
            return this.Entities.Find(id);
        }
        /// <summary>
        /// Insert entity
        /// </summary>
        /// <param name="entity">Entity</param>
        public virtual void Insert(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                this.Entities.Add(entity);

                this._context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                    foreach (var validationError in validationErrors.ValidationErrors)
                        msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
 var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }

        /// <summary>
        /// Insert entities
        /// </summary>
        /// <param name="entities">Entities</param>
        public virtual void Insert(IEnumerable<T> entities)
        {
            try
            {
                if (entities == null)
                    throw new ArgumentNullException("entities");

                foreach (var entity in entities)
                    this.Entities.Add(entity);

                this._context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                    foreach (var validationError in validationErrors.ValidationErrors)
                        msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;

                var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }

        /// <summary>
        /// Update entity
        /// </summary>
        /// <param name="entity">Entity</param>
        public virtual void Update(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                this._context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                    foreach (var validationError in validationErrors.ValidationErrors)
                        msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

                var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }

        /// <summary>
        /// Delete entity
        /// </summary>
        /// <param name="entity">Entity</param>
        public virtual void Delete(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                this.Entities.Remove(entity);

                this._context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                    foreach (var validationError in validationErrors.ValidationErrors)
                        msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

                var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }

        /// <summary>
        /// Delete entities
        /// </summary>
        /// <param name="entities">Entities</param>
        public virtual void Delete(IEnumerable<T> entities)
        {
            try
            {
                if (entities == null)
                    throw new ArgumentNullException("entities");

                foreach (var entity in entities)
                    this.Entities.Remove(entity);

                this._context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                    foreach (var validationError in validationErrors.ValidationErrors)
                        msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

                var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a table
        /// </summary>
        public virtual IQueryable<T> Table
        {
            get
            {
                return this.Entities;
            }
        }

        /// <summary>
        /// Gets a table with "no tracking" enabled (EF feature) Use it only when you load record(s) only for read-only operations
        /// </summary>
        public virtual IQueryable<T> TableNoTracking
        {
            get
            {
                return this.Entities.AsNoTracking();
            }
        }

        /// <summary>
        /// Entities
        /// </summary>
        protected virtual IDbSet<T> Entities
        {
            get
            {
                if (_entities == null)
                    _entities = _context.Set<T>();
                return _entities;
            }
        }

        #endregion
    }
}

IDbContext上下文

using System.Collections.Generic;
using System.Data.Entity;
using Nop.Core;

namespace Nop.Data
{
    public interface IDbContext
    {
        /// <summary>
        /// Get DbSet
        /// </summary>
        /// <typeparam name="TEntity">Entity type</typeparam>
        /// <returns>DbSet</returns>
        IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;

        /// <summary>
        /// Save changes
        /// </summary>
        /// <returns></returns>
        int SaveChanges();

        /// <summary>
        /// Execute stores procedure and load a list of entities at the end
        /// </summary>
        /// <typeparam name="TEntity">Entity type</typeparam>
        /// <param name="commandText">Command text</param>
        /// <param name="parameters">Parameters</param>
        /// <returns>Entities</returns>
        IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters)
            where TEntity : BaseEntity, new();

        /// <summary>
        /// Creates a raw SQL query that will return elements of the given generic type.  The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
        /// </summary>
        /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
        /// <param name="sql">The SQL query string.</param>
        /// <param name="parameters">The parameters to apply to the SQL query string.</param>
        /// <returns>Result</returns>
        IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters);

        /// <summary>
        /// Executes the given DDL/DML command against the database.
        /// </summary>
        /// <param name="sql">The command string</param>
        /// <param name="doNotEnsureTransaction">false - the transaction creation is not ensured; true - the transaction creation is ensured.</param>
        /// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
        /// <param name="parameters">The parameters to apply to the command string.</param>
        /// <returns>The result returned by the database after executing the command.</returns>
        int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters);
    }
}

This indicates the entity that you are trying to update has been deleted/modified in background/other user session.这表明您尝试更新的实体已在后台/其他用户会话中被删除/修改。 I think you guys have added rowversions in your tables and enabled concurrency control.我认为你们已经在表中添加了行版本并启用了并发控制。 The exception is telling you that a concurrent modification has occurred.例外是告诉您发生了并发修改。 You can handle this by reloading the entity and retrying the operation.您可以通过重新加载实体并重试操作来处理此问题。

If this is an MVC application using Entity Framework, it may be that you've not embedded the primary key in your View.如果这是使用实体框架的 MVC 应用程序,则可能是您没有在视图中嵌入主键。 I've had this happen when I created a new Edit View in my application, and neglected to put this in the Edit view's form: @Html.HiddenFor(model => model.XfmrTapID)当我在我的应用程序中创建一个新的编辑视图时发生了这种情况,而忽略了将它放在编辑视图的表单中: @Html.HiddenFor(model => model.XfmrTapID)

When my controller's HttpPost ActionMethod tried to process what the form returned, it deceptively gave me the OptimisticConcurrencyException.当我的控制器的 HttpPost ActionMethod 试图处理表单返回的内容时,它欺骗性地给了我 OptimisticConcurrencyException。 Make sure you check for that if it is a new MVC View.如果它是一个新的 MVC 视图,请确保检查它。

public virtual void Insert(T entity)
        {
            try
            {
                if (entity == null)
                  throw new ArgumentNullException("entity");
                this.Entities.Add(entity);
                this._context.SaveChanges();
            }
           catch  (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ex)
           {
              //Safely ignore this exception
           }
           catch (System.Data.Entity.Core.OptimisticConcurrencyException)
           {
            //Safely ignore this exception
           }                
           catch (DbEntityValidationException dbEx)
           {

            var msg = string.Empty;
            foreach (var validationErrors in dbEx.EntityValidationErrors)
                foreach (var validationError in validationErrors.ValidationErrors)
                    msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
            var fail = new Exception(msg, dbEx);
            //Debug.WriteLine(fail.Message, fail);
            throw fail;
         }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决此“System.Data.Entity.DynamicProxies”错误 - How can I solve this "System.Data.Entity.DynamicProxies" error OptimisticConcurrencyException在System.Data中不存在 - OptimisticConcurrencyException does not exist in System.Data Entity Framework Core 如何解决..Index 0-Error? - Entity Framework Core How To Solve ..Index 0-Error? 如何解决“ System.Data.Entity.Database.DefaultConnectionFactory”过时的问题? - How to solve'System.Data.Entity.Database.DefaultConnectionFactory' is obsolete? 如何解决 System.Data.Entity.Infrastructure.DbUpdateException - How to solve System.Data.Entity.Infrastructure.DbUpdateException 具有实体框架错误的C#Windows窗体应用程序:System.Data.Entity.Core.ProviderIncompatibleException - C# Windows Form Application With Entity Framework Error: System.Data.Entity.Core.ProviderIncompatibleException 如何解决错误“System.InvalidCastException - 列包含 NULL 数据” - How to solve error "System.InvalidCastException - column contains NULL data" c#错误,引发类型为&#39;System.Data.Entity.Core.EntityCommandExecutionException&#39;的异常 - c# Error as threw an exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' System.Data.Entity.Core.EntityException:“基础提供程序在打开时失败。” 错误? - System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.' Error? 如何解决无法将类型为“ System.Data.DataView”的对象转换为类型为“ System.Data.DataTable”的错误 - How to solve Unable to cast object of type 'System.Data.DataView' to type 'System.Data.DataTable' ERROR
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM