locked
How to update record using Entity Framework? RRS feed

  • Question

  • User1224379429 posted

    HI

    I am using generic repository pattern for CRUD operations. I want to update the record and I am using the below code 

     public interface IRepository<TEntity> : IDisposable
        {
            List<TEntity> GetAll();
            TEntity GetSinglEntity(Func<TEntity, bool> predicate);
            bool Delete(TEntity entity);
            bool Add(TEntity entity);
            bool Update(TEntity entity);
        }
     public class DataRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
    
     public bool Update(TEntity entity)
            {
                try
                {
                    using (xrateEntities entities = new xrateEntities())
                    {
                        entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                        // Below code is adding the new record
                        entities.Set<TEntity>().Add(entity); // How to update the entity or record
                        entities.SaveChanges();
                        return true;
                        // log here
                    }
                }
                catch (Exception exception)
                {
                    // log here
                    throw exception;
                }
                return false;
            }
    
    }

    How to update the record using Entity framework?
    Thanks

    Sunday, December 25, 2016 12:40 PM

All replies

  • User-271186128 posted

    Hi Athar Ali Khan,

    How to update record using Entity Framework?

    To update the entities, you don’t need to add “entities.Set<TEntity>().Add(entity);”.

    The Entity’s property will be replaced by the  new one which you passed in.

    And you must set the PK in the entity.  The PK is used to find which data you want to update in database.

    public class DataRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        public bool Update(TEntity entity)
        {
            try
            {
                using (xrateEntities entities = new xrateEntities())
                {
                    entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;               
                    entities.SaveChanges();
                    return true;
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return false;
    }
    }
    
    

    If you want more information about CRUD in mvc, you can refer this link:

    https://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application

    Best regards,
    Billy

     

    Monday, December 26, 2016 10:08 AM
  • User1224379429 posted

    HI

    I modified my code as below.

     public bool Update(TEntity entity)
            {
                try
                {
                    using (xrateEntities entities = new xrateEntities())
                    {
                        entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                        entities.SaveChanges();
                        return true;
                        // log here
                    }
                }
                catch (Exception exception)
                {
                    // log here
                    throw exception;
                }
            }
     DateTime asofDateTime = DateTime.ParseExact(txtAsoftimeE.Text, "MM-dd-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
                        objCurrencyDef = objCurrencyDefRepository.GetSinglEntity(trn => trn.Cur == txtCurrencyE.Text.ToUpper() && trn.AsOfTime == asofDateTime); // getting entity
                        if (objCurrencyDef != null)
                        {
                            objCurrencyDef.Cur = txtCurrencyE.Text.ToUpper(); // primary key
                            objCurrencyDef.Dece = Convert.ToDecimal(txtDeceE.Text);
                            objCurrencyDef.Direct = ddlDirectE.Value;
                            objCurrencyDef.Alert = Convert.ToDecimal(txtAlertE.Text);
                            objCurrencyDef.Area = ddlAreaE.Value;
                            objCurrencyDef.Ceiling = Convert.ToDecimal(txtCeilingE.Text);
                            objCurrencyDef.HolidaysVol = Convert.ToDecimal(txtHolidaysVolE.Text);
                            objCurrencyDef.MarketVol = Convert.ToDecimal(txtMarketVolE.Text);
                            objCurrencyDef.Unit = Convert.ToDecimal(txtUnitE.Text);
                            objCurrencyDef.IsBSF = ddlBSFE.Value;
                            objCurrencyDef.AsOfTime = Utility.GetCurrentDateTimeSec(); // primary key
    
                           
                                objCurrencyDefRepository.Update(objCurrencyDef);
    }

    I have two primary keys in the table.

    I am getting below error

    Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

    Thanks

    Wednesday, December 28, 2016 8:07 AM
  • User1224379429 posted

    Hi

    Just now I came to know that primary cannot be updated using entity framework for good reasons.

    Thanks

    Wednesday, December 28, 2016 12:15 PM