While searching for the best practivies of performing CRUD operation via EF I noticed that it is highly recommended to use Attach()
or Find()
methods before updating an entity. It works well and according to EF documentation these methods fetch the entity to context that is quite clear for me. But the followind code confused me pretty much
public void Update(object entity)
{
Record record = new Record() {
id = 1,
value = 5
};
using (SomeContext ctx = new SomeContext())
{
ctx.Entry(record).State = EntityState.Modified;
ctx.SaveChanges();
}
}
Assume we have a record with id = 1 in database. On this condition the code above will update the record (set the value to 5). The question is why it works? And then why should I use Attach()
?. As far as I understand the record wasn't attached to context in any way. I read relevant chapters of this book and the tutorial but they use 2-query-approach. Also I surfed SO but didn't find answer on my question. Help me with explanation or some good matherials, please.