Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the DBContext.Entry do?

[HttpPost] public ActionResult Edit(Movie movie) {     if (ModelState.IsValid)     {         db.Entry(movie).State = EntityState.Modified;         db.SaveChanges();         return RedirectToAction("Index");     }     return View(movie); } 

This action receives a movie model and updates it in the database.
But I can't figure out how.
The movie object isn't attached to the db, so how does entity framework know which row in the db should be updaed?

I am sure that the Entry method has something to do with it, but I don't really know what this method does. I read that it provies information but I cannot understand how by just changing the State of an entry it becomes attached and tracked by the DBContext.

like image 339
Idan Yadgar Avatar asked Feb 23 '13 21:02

Idan Yadgar


People also ask

Why do we use DbContext in MVC?

You can think of DbContext as the database connection and a set of tables, and DbSet as a representation of the tables themselves. The DbContext allows you to link your model properties (presumably using the Entity Framework) to your database with a connection string.

How does DbContext work in .NET core?

A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns. Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance.

What is entry in C#?

Entry(Object)Gets a DbEntityEntry object for the given entity providing access to information about the entity and the ability to perform actions on the entity. C# Copy. public System.Data.Entity.Infrastructure.

Should you use using with DbContext?

EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.


1 Answers

It just attaches the entity to the dataContext. Otherwise you will have to search for the entity using the primary key and then edit the value and save it.

If you have an entity that you know already exists in the database but to which changes may have been made then you can tell the context to attach the entity and set its state to Modified. http://msdn.microsoft.com/en-US/data/jj592676

like image 122
Parv Sharma Avatar answered Sep 19 '22 15:09

Parv Sharma