locked
EF core entity update RRS feed

  • Question

  • User-457790453 posted

    Is this a valid update method in repo pattern within EF core to update attached entities.

    public virtual void Update(TEntity obj)
    {
               DbSet.Update(obj);
                var attachedObj = DbSet.Local.FirstOrDefault(e => e.Id.Equals(obj.Id));
                if (attachedObj != null)
                {
                    var attachedEntry = DbContext.Entry(attachedObj);
                    attachedEntry.CurrentValues.SetValues(obj);
                }
                else
                    DbSet.Update(obj);
             }

    Thursday, April 12, 2018 8:36 PM

All replies

  • User1120430333 posted

    Why, is it not working or something?

    Friday, April 13, 2018 12:43 AM
  • User-832373396 posted

    Hi Fouad,

    Sir, for your code, I recommend that you could refer to this complete  Repository Pattern example in the .net core

    namespace GR.Data 
    { 
        public class Repository<T> : IRepository<T> where T : BaseEntity 
        { 
            private readonly ApplicationContext context; 
            private DbSet<T> entities; 
            string errorMessage = string.Empty; 
     
            public Repository(ApplicationContext context) 
            { 
                this.context = context; 
                entities = context.Set<T>(); 
            } 
            public IEnumerable<T> GetAll() 
            { 
                return entities.AsEnumerable(); 
            } 
     
            public T Get(long id) 
            { 
                return entities.SingleOrDefault(s => s.Id == id); 
            } 
            public void Insert(T entity) 
            { 
                if (entity == null) 
                { 
                    throw new ArgumentNullException("entity"); 
                } 
                entities.Add(entity); 
                context.SaveChanges(); 
            } 
     
            public void Update(T entity) 
            { 
                if (entity == null) 
                { 
                    throw new ArgumentNullException("entity"); 
                } 
                context.SaveChanges(); 
            } 
     
            public void Delete(T entity) 
            { 
                if (entity == null) 
                { 
                    throw new ArgumentNullException("entity"); 
                } 
                entities.Remove(entity); 
                context.SaveChanges(); 
            } 
     
        } 
    } 

    2 and you could download it and run it on your local :)

    With regards, Angelina Jolie

    Friday, April 13, 2018 6:20 AM