实体框架6查询返回记录,其中数据尚未保存在数据库中 [英] Entity Framework 6 query returning record with data not yet saved in the database
问题描述
我使用Entity Framework 6 Code-first创建了一个非常简单的测试项目,我试图了解变更跟踪的工作原理.
I created a very simple test project using Entity Framework 6 Code-first and I'm trying to understand how change tracking works.
在我的简单测试中,我有一个Blogs表,我插入了一个名为"User1"的Blog,在插入并保存后,我修改了用于插入的对象(name ="User1 Modifyed"),但未保存更改.之后,我查询数据库.令我惊讶的是,即使更新后我没有保存更改,数据库查询仍返回修改后的记录.这是为什么?
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?
这是我的代码:
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?
谢谢!
原始项目教程可以在这里找到: http://msdn.microsoft.com/en-us/data/jj193542.aspx
The original project tutorial can be found here: http://msdn.microsoft.com/en-us/data/jj193542.aspx
推荐答案
我最终按照@LadislavMrnka的建议查询了实体 AsNoTracking
:
I ended up querying my entities AsNoTracking
as suggested by @LadislavMrnka:
var query = from x context.YourEntities.AsNoTracking() where ... select x;
这迫使EF每次都重新加载数据.在我的情况下它可以工作,因为我只需要从返回的对象中读取一些数据,而无需保存任何更改.
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.
这篇关于实体框架6查询返回记录,其中数据尚未保存在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!