问题
I created a very simple test project using Entity Framework 6 Code-first and I'm trying to understand how change tracking works.
In my simple test I have a Blogs table and I insert a Blog with a name "User1", after inserting and saving I modify the object used to insert (name="User1 modified") but without saving changes. Right after that I query my database. For my surprise the query from the db is returning the modified record even though I did not save my changes after the update. Why is that?
Here my code:
class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.Write("Enter a name for a new Blog: ");
//var name = Console.ReadLine();
var name = "User1";
var blog = new Blog { Name = name };
db.Blogs.Add(blog);
db.SaveChanges();
//Modify my blog name but don't save changes yet!
blog.Name = "User1 modified";
// Display all Blogs from the database
var query = from b in db.Blogs
orderby b.Name
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
//item.Name comes as "User1 modified" instead of "User1" Why?????
Console.WriteLine(item.Name);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
}
How can I get the data directly from the database instead of the Context, which seems to be holding my object properties even without saving changes?
Thanks!
The original project tutorial can be found here: http://msdn.microsoft.com/en-us/data/jj193542.aspx
回答1:
The DbContext
is a unit of work and it is a feature that it returns the same object as you already have loaded. The DbContext
caches all objects loaded and provides one consistent view of the data which you can update and later save in one call to SaveChanges()
.
If you want to do separate queries from the database that don't take unsaved changes into consideration you should do that using another DbContext
.
回答2:
I ended up querying my entities AsNoTracking
as suggested by @LadislavMrnka:
var query = from x context.YourEntities.AsNoTracking() where ... select x;
How to force EF Code First to query the database?
That forces EF to reload the data each time. It works in my case because I only need to read some data form my returning objects and I'm not saving any changes.
来源:https://stackoverflow.com/questions/22207702/entity-framework-6-query-returning-record-with-data-not-yet-saved-in-the-databas