davide.gironi
davide.gironi

Reputation: 337

Get OriginalValues Entity Framework from an entity after the context is closed

i'm trying to retrive OriginalValues from a entity after the context has been closed, but i get CurrentValues. Any suggestion? Can not get entity connected to the object, i must close it. Think about a generic model, the below one is just a sample.

To let you understaind, here my sample (as reference the db can be found here: 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" => :(
    }
}

Note: this doesn't help me much: EF 5 : OriginalValues are lost when context is disposed

Upvotes: 0

Views: 1665

Answers (2)

davide.gironi
davide.gironi

Reputation: 337

As Rhumborl and Jean Hominal reply, OriginalValues is always stored in the loaded context, and are disposed with the context. So a proposed solution could be to store original values within the first context creation.

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
}

Upvotes: 0

Jean Hominal
Jean Hominal

Reputation: 16796

The problem is that, because of the way that the DbContext is responsible for maintaining original values, the second DbContext is simply unaware of them.

At a minimum, you will have to transfer these values yourself.

For example:

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);
}

Upvotes: 1

Related Questions