在上下文关闭后从实体获取OriginalValues实体框架

时间:2014-12-22 10:49:50

标签: c# entity-framework

我正在尝试在上下文关闭后从实体中检索OriginalValues,但我得到了CurrentValues。有什么建议吗? 无法获取实体连接到对象,我必须关闭它。想想一个通用模型,下面只是一个样本。

为了让你明白,这里是我的样本(作为参考,数据库可以在这里找到:http://msdn.microsoft.com/en-us/data/jj592677.aspx

public static void Sample1() 
{
    var blog = null;

    //1: get from context
    using (var context = new BloggingContext()) 
    { 
        blog = context.Blogs.Find(1);
        //suppose -> blog.Name == "Test 1";
    }

    blog.Name = "Test 2"; //set name

    //The function here set the blog name record to "Test 3", using straight SQL
    SetBlogNameUsingExternalSQL("Test 3", 1);

    //2: get original values
    using (var context = new BloggingContext()) 
    {
        context.Blogs.Attach(blog);
        var currentValues = context.Entry(blog).CurrentValues;
        //currentValues.Name is "Test 2", expected is "Test 2" => OK
        var databaseValues = context.Entry(blog).GetDatabaseValues(); 
        //databaseValues.Name is "Test 3", expected is "Test 3" => OK
        var originalValues = context.Entry(blog).OriginalValues;
        // -------> originalValues.Name is "Test 2", expected is "Test 1" => :(
    }
}

注意:这对我没什么帮助:EF 5 : OriginalValues are lost when context is disposed

2 个答案:

答案 0 :(得分:1)

问题是,由于DbContext负责维护原始值的方式,第二个DbContext根本就不知道它们。

至少,您必须自己转移这些值。

例如:

Blog blog = null;
DbPropertyValues originalBlogValues = null;

//1: get from context
using (var context = new BloggingContext()) 
{ 
    blog = context.Blogs.Find(1);
    originalBlogValues = context.Entry(blog).OriginalValues;
}

blog.Name = "Test 2";

using (var context = new BloggingContext()) 
{
    context.Blogs.Attach(blog);
    context.Entry(blog).OriginalValues.SetValues(originalBlogValues);
}

答案 1 :(得分:0)

当Rhumborl和Jean Hominal回复时,OriginalValues始终存储在已加载的上下文中,并随上下文一起处理。因此,建议的解决方案可以是在第一个上下文创建中存储原始值。

var originalValues = null;

//1: get from context
using (var context = new BloggingContext()) 
{ 
    blog = context.Blogs.Find(1);
    //suppose -> blog.Name == "Test 1";
    originalValues = context.Entry(blog).OriginalValues; //load OriginalValues here
}