Home » Ado.Net » Entity Framework » Entity Framework (EF) modifying an instance that is already in the context

Entity Framework (EF) modifying an instance that is already in the context

If you set an entity state to modify without having this one loaded and you save everything then you have no problem. However, if you got the entity from a previous load, this one is inside the local context which can raise the following exception.

Attaching an entity of type ‘Model.Entities.Users.ApplicationUser’ failed because another entity of the same type already has the same primary key value. This can happen when using the ‘Attach’ method or setting the state of an entity to ‘Unchanged’ or ‘Modified’ if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the ‘Add’ method or the ‘Added’ entity state to track the graph and then set the state of non-new entities to ‘Unchanged’ or ‘Modified’ as appropriate.

EventViewerEntityFrameworkModifyError

This is very annoying and unfortunate that Entity Framework (ef) does not have something more intelligent to handle those case. In short, you have to detach the local version and set to modify the entity you are modifying. This scenario is pretty common if you receive the object from a web request and you want to save the entity. Between the request that contains the object and the time you change the state to modify (saving code) you may have loaded a list that contains your entity or you may have loaded a part of this entity for validation purpose. Nonetheless, you have to handle this case if you want to save this entity.

A way to do it is to navigate inside the local of the DbSet to see if this one is there. If the entity is present, then you detach.

var local = yourDbContext.Set<YourModel>()
                         .Local
                         .FirstOrDefault(f => f.Id == yourModel.Id);
if (local != null)
{
  yourDbContext.Entry(local).State = EntityState.Detached;
}
yourDbContext.Entry(applicationModel).State = EntityState.Modified;

As you can see, we first verify if the entity is present inside the DbSet. If it is null, then we detach the local entity. In all case, we set to modify the entity (applicationModel) to have this one considered by Entity Framework to be updated.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

43 Responses so far.

  1. CZ says:

    hi Patrick,

    What is “applicationModel” in this line of code yourDbContext.Entry(applicationModel).State = EntityState.Modified;

    all I have at this point is TEntity entity as a parameter, please share your thoughts on how to fix this issue.

    TIA
    CZ

    • Hello, applicationModel object is the object/instance you are trying to save with Entity Framework. Good catch, I’ll edit the text to make it more clear.

      • CZ says:

        Thanks for the quick response Patrick. Actually I am getting this error when trying to Attach an entity before Removing. This is a Delete operation

        public virtual void Delete(TEntity entity)
        {
        try
        {
        DbSet.Attach(entity);
        DbSet.Remove(entity);
        }
        catch
        {
        throw;
        }
        }

        Where entity is what I want to delete. DbSet.Local is loading all the entities and I thing that is the problem, I tried to empty DbSet.Local and then mark it as modified / Unchanged but it is throwing the same error.

        Any help is appreciated .

        TIA
        CZ

        • What about you try to see if it in local, if yes you delete that one.

          public virtual void Delete(TEntity entity) where TEntity : IEntity
          {
          var local = yourDbContext.Set()
          .Local
          .FirstOrDefault(f => f.Id == entity.Id);

          if (local != null) //It’s in the local!
          {
          yourDbContext.Entry(local).State = EntityState.Deleted;
          }
          else
          {
          yourDbContext.Entry(applicationModel).State = EntityState.Deleted;
          }
          }

  2. Sylpheed says:

    Hi, I have the same problem. But for me, it crashes right after I try attaching the supposedly detached entity. I tried your code and “local” always returns null.

    • If local is null, than it means that the Entity is not yet in the DbContext. What is the exception that you are getting?

      • Niraj says:

        I am having the same issue, as experienced by Sylpheed.

        Local entity always return null, but if I try and attach the entity, it will result in the exception you have mentioned above. Below is my code.

        public void Deactivate(User user)
        {
        if (user.Id == 0) return;

        using (var dbContext = new MyContext())
        {
        var localEntity = dbContext.Set().Local.FirstOrDefault(u => u.Id == user.Id);

        if (localEntity != null)
        dbContext.Entry(localEntity).State = EntityState.Detached;

        user.IsActive = false;
        user.DeactivatedOn = DateTime.Now;

        dbContext.Entry(user).State = EntityState.Modified; //Exception occurs here
        dbContext.SaveChanges();
        }
        }

  3. abdullah says:

    it works and saved my hours

  4. reza says:

    Hi, I have the same problem. But for me, my method is generic
    Delete (T entity)
    and I can not assume input entity always has Id field.

    • Your can be more specific “where T : ” This way you can have access to a unique identifier. Your entities can implement the interface and just redirect to the unique identifer. For example, if the unique identifier is “PersonId” Your class implement the interface which force to implement public get Id{return this.PersonId;}.

  5. Gládiston Queiroz says:

    It´s Works! Thank you.

  6. Nick says:

    Hi Patrick.
    The value i tried to edit is DateTime. And if i try your example return me a NullReferenceExeption.
    Also here -> yourDbContext.Entry(local).State = EntityState.Detached; -> local can`t be of a DateTime type.
    I have a posts with some created date and i want to keep that date when edit any post. I can`t bellieve there`s no better way to do this?

  7. bruno kingma says:

    Hi Patrick I´m getting the same error then doing this.

    var empresa = _empresaAppService.ObterPorId(id);
    var empresa = Mapper.Map(empresaViewModel);
    _empresaRepository.Update(empresa);

    public EmpresaViewModel ObterPorId(int id)
    {
    var empresa = _empresaRepository.GetById(id);
    return Mapper.Map(empresa);
    }

    public virtual TEntity GetById(int id)
    {
    return DbSet.Find(id);
    }

    public virtual void Update(TEntity obj)
    {
    var entry = Context.Entry(obj);
    DbSet.Attach(obj);
    entry.State = EntityState.Detached;
    Context.SaveChanges();

    }

    • Robert B says:

      Bruno – doesn’t look like you are checking the local cache of the context. If you look at Patrick’s code, he’s checking the the Context.Set().Local to see if the object exists prior to the Attach call or setting the state.

  8. bruno kingma says:

    Any one?

  9. Ghassem says:

    what if we are using Repository Pattern, For example for delete and update:

    public void UpdateEntity(T entity)
    {

    dbSet.Attach(entity);
    dbContext.Entry(entity).State = EntityState.Modified;
    }

    public void DeleteEntity(T entity)
    {
    if (dbContext.Entry(entity).State == EntityState.Detached)
    dbSet.Attach(entity);
    dbSet.Remove(entity);
    }

    • @Ghassem the article works with Repository Pattern and for the delete and update scenario. As mentioned : “you have to detach the local version and set to modify the entity you are modifying. “

      • Ghassem says:

        Thanks Patrick, I tried but still have the same problem! Let me try again perhaps I have not got the point!
        Many thanks for quick answer!

      • Virender singh says:

        Can you please send the code how we can detach the local without having an id on where clause because it is a generic so we cant refer id in where clause.

        • Hello, I do not have the source code. However, you can have an ID with generic as long as the type T as a generic constraint. Here is some documentation about it : https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters

          • Virender singh says:

            #region Old implementation

            //using System;
            //using System.Collections.Generic;
            //using System.Linq;
            //using System.Text;
            //using System.Threading.Tasks;
            //using SchoolApp.Model;
            //using System.Data.Entity;
            //using System.Linq.Expressions;

            //namespace SchoolApp.Repository
            //{
            //#pragma warning disable CS0436 // Type conflicts with imported type
            // ///
            // /// This is a generic repository which contains generic CRUD functions
            // /// This is an abstraction layer between the data access layer and business logic layer
            // /// This will insulate the application from changes in the data store
            // ///
            // ///
            // public abstract class GenericRepository : IGenericRepository
            //#pragma warning restore CS0436 // Type conflicts with imported type
            // where T : BaseEntity
            // {
            // protected DbContext _entities;
            // protected readonly IDbSet _dbset;

            // ///
            // /// The parameterised constructor which takes dbcontext as parameter
            // ///
            // ///
            // public GenericRepository(DbContext context)
            // {

            // _entities = context;
            // _dbset = context.Set();
            // }

            // ///
            // /// This function gets all the records of entity
            // ///
            // ///
            // public virtual IEnumerable GetAll()
            // {
            // return _dbset.AsNoTracking().AsEnumerable();
            // //return _dbset.AsQueryable();
            // }

            // ///
            // /// This function find by the lambda expression as filter
            // ///
            // ///
            // ///
            // public IEnumerable FindBy(System.Linq.Expressions.Expression<Func> predicate)
            // {
            // IEnumerable query = _dbset.Where(predicate).AsEnumerable();
            // return query;
            // }

            // ///
            // /// This function add the record in the table corresponding to entity
            // ///
            // ///
            // ///
            // public virtual T Add(T entity)
            // {
            // return _dbset.Add(entity);
            // }

            // ///
            // /// This function delete the record in the table corresponding to entity
            // ///
            // ///
            // ///
            // public virtual T Delete(T entity)
            // {
            // return _dbset.Remove(entity);
            // }

            // ///
            // /// This function edit the record in the table corresponding to entity
            // ///
            // ///
            // public virtual void Edit(T entity)
            // {
            // // if (_entities.Entry(entity).State == EntityState.Modified)
            // // {
            // // _entities.Entry(entity).State = EntityState.Detached;
            // _entities.Entry(entity).State = EntityState.Modified;
            // // }
            // //_entities.SaveChanges();
            // }

            // ///
            // /// This function save the record in the table corresponding to entity
            // ///
            // public virtual void Save()
            // {
            // // try
            // // {
            // _entities.SaveChanges();
            // //}
            // //catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ex)
            // //{
            // // var entry = ex.Entries.Single();
            // // entry.OriginalValues.SetValues(entry.GetDatabaseValues());
            // // _entities.SaveChanges();
            // //}
            // }
            // public void Reload(T entity)
            // {
            // _entities.Entry(entity).ReloadAsync();
            // }
            // //avinash
            // public virtual List Get(Expression<Func> filter = null,
            // Func<IQueryable, IOrderedQueryable> orderBy = null, string includeProperties = “”, bool ignoreDeleted = false)
            // {
            // var query = GetQuery(filter, includeProperties, ignoreDeleted);

            // if (orderBy != null)
            // return orderBy(query).ToList();

            // return query.ToList();
            // }

            // public IQueryable GetQuery(Expression<Func> filter = null, string includeProperties = “”, bool ignoreDeleted = false)
            // {
            // IQueryable query = _dbset;

            // Type[] types = typeof(T).GetInterfaces();

            // //here we re filter deleted item
            // //if (types.Contains(typeof(IFlagRemove)) && !ignoreDeleted)
            // //{
            // // query = (query as IQueryable).Where(e => !e.IsDeleted).Cast();
            // //}

            // if (filter != null)
            // {
            // query = query.Where(filter);
            // }

            // foreach (var includeProperty in includeProperties.Split
            // (new char[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries))
            // {
            // query = query.Include(includeProperty);
            // }

            // return query;
            // }
            // }
            //}

            #endregion

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using SchoolApp.Model;
            using System.Data.Entity;
            using System.Linq.Expressions;

            namespace SchoolApp.Repository
            {
            #pragma warning disable CS0436 // Type conflicts with imported type
            ///
            /// This is a generic repository which contains generic CRUD functions
            /// This is an abstraction layer between the data access layer and business logic layer
            /// This will insulate the application from changes in the data store
            ///
            ///
            public abstract class GenericRepository : IGenericRepository//, IDisposable
            #pragma warning restore CS0436 // Type conflicts with imported type
            where T : BaseEntity
            {
            protected DbContext _entities;
            protected readonly IDbSet _dbset;
            bool _isDisposed = false;
            T _baseEntity;

            ///
            /// The parameterised constructor which takes dbcontext as parameter
            ///
            ///
            public GenericRepository(DbContext context)
            {
            // context = new SchoolAppContext();

            _entities = new SchoolAppContext(); //GetDbContext();
            //_entities.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

            _dbset = _entities.Set();

            }

            //private DbContext GetDbContext()
            //{
            // return this.GetDbContext(false);
            //}

            //protected virtual DbContext GetDbContext(bool canUseCachedContext)
            //{
            // if (_entities != null)
            // {
            // if (canUseCachedContext)
            // {
            // return _entities;
            // }
            // else
            // {
            // _entities.Dispose();
            // }
            // }

            // _entities = new SchoolAppContext();

            // return _entities;
            //}

            //public void Dispose()
            //{
            // this.Dispose(true);
            //}

            //protected virtual void Dispose(bool isDisposing)
            //{
            // if (!_isDisposed)
            // {
            // if (isDisposing)
            // {
            // // Clear down managed resources.

            // if (_entities != null)
            // _entities.Dispose();
            // }

            // _isDisposed = true;
            // }
            //}

            ///
            /// This function gets all the records of entity
            ///
            ///
            public virtual IEnumerable GetAll()
            {
            return _dbset.AsEnumerable();
            }

            ///
            /// This function find by the lambda expression as filter
            ///
            ///
            ///
            public IEnumerable FindBy(System.Linq.Expressions.Expression<Func> predicate)
            {
            IEnumerable query = _dbset.Where(predicate).AsEnumerable();
            return query;
            }

            ///
            /// This function add the record in the table corresponding to entity
            ///
            ///
            ///
            public virtual T Add(T entity)
            {
            var returnObject = _dbset.Add(entity);
            Save();
            return returnObject;
            }

            ///
            /// This function delete the record in the table corresponding to entity
            ///
            ///
            ///
            public virtual T Delete(T entity)
            {
            _entities.Entry(entity).State = EntityState.Deleted;
            //var returnObject = _dbset.Remove(entity);
            Save();
            return entity;
            }

            ///
            /// This function edit the record in the table corresponding to entity
            ///
            ///
            public virtual void Edit(T entity)
            {
            _baseEntity = entity;
            // if (_entities.Entry(entity).State == EntityState.Modified)
            // {
            // _entities.Entry(entity).State = EntityState.Detached;

            // }
            //_entities.SaveChanges();

            //var local = _entities.Set()
            // .Local
            // .FirstOrDefault(f => f. == ((BaseEntity)entity));
            //if (local != null)
            //{
            // yourDbContext.Entry(local).State = EntityState.Detached;
            //}
            //yourDbContext.Entry(applicationModel).State = EntityState.Modified;

            try
            {
            //Console.WriteLine(_entities.Entry(entity).State);
            // _dbset.Attach(entity);
            //_entities.Entry(entity).State = EntityState.Detached;

            if (!_dbset.Local.Contains(entity))
            {
            _dbset.Attach(entity);
            }

            _entities.Entry(entity).State = EntityState.Modified;
            }
            catch (Exception ex)
            {
            throw;

            //_entities.Entry(entity).State = EntityState.Detached;
            //if (!_dbset.Local.Contains(entity))
            //{
            // _dbset.Attach(entity);
            //}
            //_entities.Entry(entity).State = EntityState.Modified;

            //var entry = ex.Entries.Single();
            //entry.OriginalValues.SetValues(entry.GetDatabaseValues());
            //_entities.SaveChanges();
            }
            }

            ///
            /// This function save the record in the table corresponding to entity
            ///
            public virtual void Save()
            {
            try
            {
            _entities.SaveChanges();
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ex)
            {
            throw;
            }
            }
            public void Reload(T entity)
            {
            _entities.Entry(entity).ReloadAsync();
            }
            //avinash
            public virtual List Get(Expression<Func> filter = null,
            Func<IQueryable, IOrderedQueryable> orderBy = null, string includeProperties = “”, bool ignoreDeleted = false)
            {
            var query = GetQuery(filter, includeProperties, ignoreDeleted);

            if (orderBy != null)
            return orderBy(query).ToList();

            return query.ToList();
            }

            public IQueryable GetQuery(Expression<Func> filter = null, string includeProperties = “”, bool ignoreDeleted = false)
            {
            IQueryable query = _dbset;

            Type[] types = typeof(T).GetInterfaces();

            //here we re filter deleted item
            //if (types.Contains(typeof(IFlagRemove)) && !ignoreDeleted)
            //{
            // query = (query as IQueryable).Where(e => !e.IsDeleted).Cast();
            //}

            if (filter != null)
            {
            query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
            (new char[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries))
            {
            query = query.Include(includeProperty);
            }

            return query;
            }
            }
            }

            This is the code and BaseEntity class has an Id field. Can you please guide me how we can implement in this.

          • Virender singh says:

            Please provide me a solution for edit method.

          • Virender singh says:

            I have defined the constraint for generic type as a base class wherein i have defined id field but still i am not getting id in lambda expression.

            var local = _dbset.Local.FirstOrDefault(f => f. == entity.ID);
            if (local != null)

          • Virender singh says:

            I request you to please provide me the solution asap

          • Virender singh says:

            I pasting the code again

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using SchoolApp.Model;
            using System.Data.Entity;
            using System.Linq.Expressions;

            namespace SchoolApp.Repository
            {
            #pragma warning disable CS0436 // Type conflicts with imported type
            ///
            /// This is a generic repository which contains generic CRUD functions
            /// This is an abstraction layer between the data access layer and business logic layer
            /// This will insulate the application from changes in the data store
            ///
            ///
            public abstract class GenericRepository : IGenericRepository//, IDisposable
            #pragma warning restore CS0436 // Type conflicts with imported type
            where T : BaseEntity
            {
            protected DbContext _entities;
            //protected DbContext _entitiesGet;
            protected readonly IDbSet _dbset;
            // protected readonly IDbSet _dbsetGet;
            bool _isDisposed = false;

            ///
            /// The parameterised constructor which takes dbcontext as parameter
            ///
            ///
            public GenericRepository(DbContext context)
            {
            _entities = new SchoolAppContext();

            //_entities = GetDbContext();
            //_entities.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

            _dbset = _entities.Set();

            //_entitiesGet = new SchoolAppContext();
            //_dbsetGet = _entitiesGet.Set();
            }

            //private DbContext GetDbContext()
            //{
            // return this.GetDbContext(false);
            //}

            //protected virtual DbContext GetDbContext(bool canUseCachedContext)
            //{
            // if (_entities != null)
            // {
            // if (canUseCachedContext)
            // {
            // return _entities;
            // }
            // else
            // {
            // _entities.Dispose();
            // }
            // }

            // _entities = new SchoolAppContext();

            // return _entities;
            //}

            //public void Dispose()
            //{
            // this.Dispose(true);
            //}

            //protected virtual void Dispose(bool isDisposing)
            //{
            // if (!_isDisposed)
            // {
            // if (isDisposing)
            // {
            // // Clear down managed resources.

            // if (_entities != null)
            // _entities.Dispose();
            // }

            // _isDisposed = true;
            // }
            //}

            ///
            /// This function gets all the records of entity
            ///
            ///
            public virtual IQueryable GetAll()
            {
            // _entitiesGet = DbContextExtensions.RefreshEntites(_entitiesGet, System.Data.Entity.Core.Objects.RefreshMode.StoreWins);
            return _dbset.AsQueryable();
            }

            ///
            /// This function find by the lambda expression as filter
            ///
            ///
            ///
            public IEnumerable FindBy(System.Linq.Expressions.Expression<Func> predicate)
            {
            IEnumerable query = _dbset.Where(predicate).AsEnumerable();
            return query;
            }

            ///
            /// This function add the record in the table corresponding to entity
            ///
            ///
            ///
            public virtual T Add(T entity)
            {
            var returnObject = _dbset.Add(entity);
            Save();
            return returnObject;
            }

            ///
            /// This function delete the record in the table corresponding to entity
            ///
            ///
            ///
            public virtual T Delete(T entity)
            {
            _entities.Entry(entity).State = EntityState.Deleted;
            //var returnObject = _dbset.Remove(entity);
            Save();
            return entity;
            }

            ///
            /// This function edit the record in the table corresponding to entity
            ///
            ///
            public virtual void Edit(T entity)
            {
            // if (_entities.Entry(entity).State == EntityState.Modified)
            // {
            // _entities.Entry(entity).State = EntityState.Detached;

            // }
            //_entities.SaveChanges();

            try
            {
            //Console.WriteLine(_entities.Entry(entity).State);
            // _dbset.Attach(entity);
            //_entities.Entry(entity).State = EntityState.Detached;

            var local = _dbset.Local.FirstOrDefault(f => f. == entity.ID);
            if (local != null)

            if (!_dbset.Local.Contains(entity))
            {
            _dbset.Attach(entity);
            }

            _entities.Entry(entity).State = EntityState.Modified;
            }
            catch (Exception ex)
            {
            throw;

            //_entities.Entry(entity).State = EntityState.Detached;
            //if (!_dbset.Local.Contains(entity))
            //{
            // _dbset.Attach(entity);
            //}
            //_entities.Entry(entity).State = EntityState.Modified;

            //var entry = ex.Entries.Single();
            //entry.OriginalValues.SetValues(entry.GetDatabaseValues());
            //_entities.SaveChanges();
            }
            }

            ///
            /// This function save the record in the table corresponding to entity
            ///
            public virtual void Save()
            {
            try
            {
            _entities.SaveChanges();
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ex)
            {
            throw;
            }
            }
            public void Reload(T entity)
            {
            _entities.Entry(entity).ReloadAsync();
            }
            //avinash
            public virtual List Get(Expression<Func> filter = null,
            Func<IQueryable, IOrderedQueryable> orderBy = null, string includeProperties = “”, bool ignoreDeleted = false)
            {
            var query = GetQuery(filter, includeProperties, ignoreDeleted);

            if (orderBy != null)
            return orderBy(query).ToList();

            return query.ToList();
            }

            public IQueryable GetQuery(Expression<Func> filter = null, string includeProperties = “”, bool ignoreDeleted = false)
            {
            IQueryable query = _dbset;

            Type[] types = typeof(T).GetInterfaces();

            //here we re filter deleted item
            //if (types.Contains(typeof(IFlagRemove)) && !ignoreDeleted)
            //{
            // query = (query as IQueryable).Where(e => !e.IsDeleted).Cast();
            //}

            if (filter != null)
            {
            query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
            (new char[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries))
            {
            query = query.Include(includeProperty);
            }

            return query;
            }
            }
            }

          • Virender singh says:

            Thanks

            It is working fine now

          • Virender singh says:

            Hi Patrick,

            There is one more issue that the data in the context is not getting refreshed.

  10. Ghassem says:

    Many Thanks Patrick, my problem resolved … thank you for your solution!

  11. Ghassem says:

    It is just like your code, Well, as you know in Repository Pattern we only deal with generic type as …. so I had to do checking attachment like your nice code in a layer using the Repository Pattern to do CRUD operations. For example for BizContact class which is business class for Contact entity, I added following method:

    DataRepository db { get; set; }

    public void CheckEntityAttachment(Contact entity)
    {
    var local = db.dbSet.Local.FirstOrDefault(F => F.ID == entity.ID);
    if (local != null)
    {
    db.dbContext.Entry(local).State = System.Data.Entity.EntityState.Detached;
    }
    }

    where dbSet is a public propery of DbContext type and dbContext is a public propery of DbSet type in Repository class!
    And then in Repository class for Update:
    public void UpdateEntity(T entity)
    {
    dbSet.Attach(entity);
    dbContext.Entry(entity).State = EntityState.Modified;
    }
    My error resolved!

  12. Marko says:

    This is great. Works perfectly! Thx

  13. Ziad says:

    It’s Worked for me. Thank you man

  14. JJ says:

    Hi ,

    I am getting the following error, while trying to update the entity

    Please help me out.

    {“another entity of the same type already has the same primary key value. This can happen when using the ‘Attach’ method or setting the state of an entity to ‘Unchanged’ or ‘Modified’ if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the ‘Add’ method or the ‘Added’ entity state to track the graph and then set the state of non-new entities to ‘Unchanged’ or ‘Modified’ as appropriate.”}

    While using the following code

    public void UpdateRemittance(Remittance entity)
    {
    Guard.ArgumentNotNull(entity, “entity”);

    if (entity.Id > 0)
    {
    this.Context.Entry(entity).State = EntityState.Detached;
    this.Context.Remittances.Attach(entity);
    this.Context.Entry(entity).State = EntityState.Modified;
    }
    else
    {
    this.AddRemittance(entity);
    }
    }

  15. majid nawaz says:

    Thanks Issue Resolve

  16. Isaac Sultan says:

    Thanks. Save me hours

  17. Joe tusoy says:

    Thanks. I already used my whole day yesterday trying to solve this. Thanks for posting the solution.

  18. Thanks. I was stuck on this for hours. Works great!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.