ErocM
ErocM

Reputation: 4662

entity records not updating

I have the following method:

public static void UpdatePpsTransaction(IEnumerable<PpsTransaction> ppsTransaction)
{
  using (var context = PpsEntities.DefaultConnection())
  {
    foreach (var trans in ppsTransaction)
    {
      context.PpsTransactions.Attach(trans);
    }
    context.SaveChanges();
  }
}

}

I was removing these records but I ended up creating a field IsProcessed which I am now setting to true. Now I am updating the records instead of deleting them, keeping them for record keeping.

Anyhow, I am not getting any errors but it is not updating the record.

Any suggestions?

Upvotes: 0

Views: 43

Answers (2)

Tobias
Tobias

Reputation: 2840

You're not telling EF that you have made any changes, try to use the Entry method, on your Context:

public static void UpdatePpsTransaction(IEnumerable<PpsTransaction> ppsTransaction)
{
  using (var context = PpsEntities.DefaultConnection())
  {
    foreach (var trans in ppsTransaction)
    {
      context.Entry(trans).State = EntityState.Modified;
    }
    context.SaveChanges();
  }
}

This way, the entities will be attached to the context in a modified stated, so when you call SaveChanges(), these will be saved.

This will only work if the entities already exists in the database, which they should.

Upvotes: 3

Matt M
Matt M

Reputation: 3779

From msdn:

If you have an entity that you know already exists in the database but which is not currently being tracked by the context then you can tell the context to track the entity using the Attach method on DbSet. The entity will be in the Unchanged state in the context. Note that no changes will be made to the database if SaveChanges is called without doing any other manipulation of the attached entity. This is because the entity is in the Unchanged state.

Here is the link

Upvotes: 0

Related Questions