简体   繁体   中英

Does the ObjectContext change for each result set?

There are a number of examples showing how to use ObjectContext to get results from a multi-result set stored procedure when using Entity Framework.
These examples always take the DbContext , cast it to a IObjectContextAdapter , and get the ObjectContext , even if they did the same thing a few lines up.

Example from MSDN (original comments removed to simplify and highlight my comments):

using (var db = new BloggingContext())
{
    db.Database.Initialize(force: false);
    var cmd = db.Database.Connection.CreateCommand();
    cmd.CommandText = "[dbo].[GetAllBlogsAndPosts]";
    try
    {
        db.Database.Connection.Open();
        var reader = cmd.ExecuteReader();
        var blogs = ((IObjectContextAdapter)db)
            .ObjectContext                                              //First Time
            .Translate<Blog>(reader, "Blogs", MergeOption.AppendOnly);
        foreach (var item in blogs)
        { 
            Console.WriteLine(item.Name);
        }

        reader.NextResult();
        var posts = ((IObjectContextAdapter)db)
            .ObjectContext                                              //Second Time
            .Translate<Post>(reader, "Posts", MergeOption.AppendOnly);

        foreach (var item in posts)
        {
            Console.WriteLine(item.Title);
        }
    }
    finally
    {
        db.Database.Connection.Close();
    }
}

My stored procedures return many result sets, so I would like to simplify the code as much as possible by copying the reference to ObjectContext to a local variable, but I am not sure if doing so will cause issues.
I did find an article which indicates that "Conceptually 'DbContext' is the same as 'ObjectContext'."
I have not found anything explicitly indicating the scope and lifetime of the object instance.
The documentation for ObjectContext is a bit lacking in details.

I prefer a link to the official documentation supporting any answer.

DbContext is a wrapper around an ObjectContext . So it contains one ObjectContext instance that you have access to through the IObjectContextAdapter interface. IObjectContextAdapter.ObjectContext will always return the same instance.

If you want to be absolutely sure, just check the output of

Console.WriteLine(((IObjectContextAdapter)db).ObjectContext.GetHashCode());
Console.WriteLine(((IObjectContextAdapter)db).ObjectContext.GetHashCode());

It will show the same value twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM