The operation cannot be completed because the DbContext has been disposed error

后端 未结 8 2000
情歌与酒
情歌与酒 2020-11-29 09:22

I\'m new to EF and I\'m trying to use an extension method which converts from my Database type User to my info class UserInfo.
I\'m using data

相关标签:
8条回答
  • 2020-11-29 09:44

    Change this:

    using (var dataContext = new dataContext())
    {
        users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);
    
        if(users.Any())
        {
            ret = users.Select(x => x.ToInfo()).ToList(); 
        }
    
     }
    

    to this:

    using (var dataContext = new dataContext())
    {
        return = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false).Select(x => x.ToInfo()).ToList();
    } 
    

    The gist is that you only want to force the enumeration of the context dataset once. Let the caller deal with empty set scenario, as they should.

    0 讨论(0)
  • 2020-11-29 09:47

    The reason why it is throwing the error is the object is disposed and after that we are trying to access the table values through the object, but object is disposed.Better to convert that into ToList() so that we can have values

    Maybe it isn't actually getting the data until you use it (it is lazy loading), so dataContext doesn't exist when you are trying to do the work. I bet if you did the ToList() in scope it would be ok.

    try
    {
        IQueryable<User> users;
        var ret = null;
    
        using (var dataContext = new dataContext())
        {
            users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);
    
            if(users.Any())
            {
                ret = users.Select(x => x.ToInfo()).ToList(); 
            }
    
         }
    
       Return ret;
    }
    catch (Exception ex)
    {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题