Search code examples
entity-frameworkdbcontextupdating

Entity Framework: updated record being inserted (instead of updated)


I'm using the following code to UPDATE certain records from the db:

        IList<Item> list;
        using (DbContext context = new DbContext()
        {
            list = Item.ToList();
            foreach (Item item in list)
            {
                // attach the item
                context.Item.Attach(item);

                item.Updated = DateTime.Now; 
                context.Items.Add(item);
                context.SaveChanges();
             }
        }

The problem is that EF is INSERTING a new item instead of updating the updated item... I've searched abit on the site and saw a suggestion to attach the item to the DbContext, but thats not working either? What am i doing wrong?


Solution

  • The procedure should be:

    using (DbContext context = new DbContext()
    {
        foreach (Item item in list)
        {
            item.Updated = DateTime.Now; 
            context.Entry(item).State = EntityState.Modified;//attaches automatically
        }
        context.SaveChanges();
    }
    

    You are calling Add which means INSERT.