开发者

Error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

I use asp.net and EF 4 in C#.

I have a DetailsView with associated a ObjectDataSource.

<asp:ObjectDataSource ID="uxEntityDataSourceAuthors" runat="server" 
        SelectMethod="GetAuthors" 
        TypeName="WebProject.Web.Cms.AdminCms.Sections.CmsContents.ContentInformation">
    </asp:ObjectDataSource>

This the code for the Method:


    public IEnumerable<CmsAuthor> GetAuthors()
    {
    if (Roles.IsUserInRole("CMS-AUTHOR"))
    {
    using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
    {
                            // Display all Authors for specific logged-in User.
                            // Get Guid for current logged-in User.
  开发者_高级运维                          MembershipUser myLoggedinUser = Membership.GetUser();
                            Guid myUserGuid = (Guid)myLoggedinUser.ProviderUserKey;
                            // Get list of Authors filtering my current logged-in User.
                            var myAuthorsForAuthor = from a in context.CmsAuthors
                                                     where a.UserId == myUserGuid
                                                     orderby a.LastName ascending
                                                     select a;
                            return myAuthorsForAuthor.AsEnumerable();
                        }
                    }
                    return null;  
 }

When I'm running the code I receive this error:

 The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. 

Any idea what I'm doing wrong and how to fix it?


You're closing the CmsConnectionStringEntityDataModel called context before getting the data. Remember that AsEnumerable() will return a lazy enumerator, no data has been read from the source when you return and dispose of `context.

Use ToArray() (or ToList()) to ensure you get the data into memory before closing the source.


Calling AsEnumerable does not enumerate the collection it just changes it from IQeuryable<T> to IEnumerble<T>. You are disposing of the ObjectContext before the data is fetched from the database. Use ToList() which will enumerate the collection and fetch the data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜