Hello There, Guest!
View New Posts  |  View Today's Posts
[C#] EF - dbcontext has been disposed

  • 0 Vote(s) - 0 Average


05-29-2014, 02:40 AM #1
Lee Stevens
Senior Member
***
Posts: 345 Threads:54 Joined: Feb 2012 Reputation: 12

EF - dbcontext has been disposed
Hi All,

Me again i'm new to Entity Framework and followed this guide: http://msdn.microsoft.com/en-us/data/jj193542

I've created my Entity's and some "help" functions to get Records/Add/Remove

Code:
public static IEnumerable<EntIPRange> getIPRanges()
        {
            IEnumerable<EntIPRange> _getIPRanges;
            using (var context = new EntManagerDBContext())
            {
                _getIPRanges = (from m in context.IPRanges orderby m.EntIPRangeId select m);
            }
            return _getIPRanges;
        }

        public static int Count()
        {
            using (var context = new EntManagerDBContext())
            {
                return (from m in context.IPRanges orderby m.EntIPRangeId select m).Count();
            }
        }

[img=http://s29.postimg.org/f0qwiisoz/Entity.jpg]

This works perfectly on my main form but once i create a sub form it returns the Exception "The operation cannot be completed because the DbContext has been disposed"

[img=http://s14.postimg.org/wvaco64x9/Disposed.jpg]

Any idea why this happens are the using creates a new context?

Thanks,
Lee.

Update i solved the issue by adding .ToList after reading here: http://stackoverflow.com/questions/21212...osed-using that seems to of fixed it - yay!
This post was last modified: 05-29-2014, 03:27 AM by Lee Stevens.

05-29-2014, 12:22 PM #2
Null
Moderator
*****
Moderators
Posts: 130 Threads:23 Joined: Feb 2012 Reputation: 4

RE: EF - dbcontext has been disposed
Glad that you solved your problem, deferred execution can be confusing for people new to IQueryable and IEnumerable.

If I may offer some constructive criticism, your first method getIpRanges, can be rewritten as follows:

Code:
public static IEnumerable<EntIPRange> GetIPRanges()
{
    using (var context = new EntManagerDBContext())
    {
        return
            from m in context.IPRanges
            orderby m.EntIPRangeId
            select m;
    }
}

The intermediate variable and the parentheses surrounding the query were redundant so I removed them. Additionally, I adapted pascal casing for the method name.

More impressively, your second method, Count, can be made far more terse:

Code:
public static int Count()
{
    using (var context = new EntManagerDBContext())
    {
        return context.IPRanges.Count();
    }
}

Clearly the ordering and projection (select) were redundant.

05-29-2014, 03:11 PM #3
Lee Stevens
Senior Member
***
Posts: 345 Threads:54 Joined: Feb 2012 Reputation: 12

RE: EF - dbcontext has been disposed
Thank you ByteBlast, yes after looking at more example i noticed i could do the same as yours and updated my functions :)




Forum Jump:



Users browsing this thread: 1 Guest(s)