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












0















This question has been asked a lot of times. I think I solved my problem but since I am a beginner and still learning I need your reassurance.



I made a Extension method for the Logged In User But when I use it in my Controller it gives me the error in title.




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




So I searched and experimented and adding this line of code
in the controller solved my problem.



db.Users.Attach(LoggedUser);


However I am not sure if my answer is correct, since a lot of answers about this question were to disable the Lazy Loading but I didn't end up using it.



Something like this.



public class MyDbContext : DbContext
{
public MyDbContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}


Here is my Extension method:



 public static ApplicationUser GetLoggedInUserInDB(this System.Security.Principal.IPrincipal _User)
{
using (var db = new ApplicationDbContext())
{
string userId = _User.Identity.GetUserId();
var LoggedUser = db.Users.Find(userId);
return LoggedUser;
}
}


My Controller:



public class MainPageController : ApiController
{
[Route("Personal_Project/Main_Page_Personal_Project/UserUnfo")]
[ResponseType(typeof(string))]
[Authorize]
public IHttpActionResult GetUserInfo()
{
using (var db = new ApplicationDbContext())
{
var LoggedUser = User.GetLoggedInUserInDB();
//db.Users.Attach(LoggedUser); // This is what I added to solve my problem.
return Ok(new UserInfoModel
{
Name = LoggedUser.UserName,
Reputation = LoggedUser.Reputation,
UserLevel = LoggedUser.UserLevel
});
}
}
}


So is 'My' solution here good? Just adding:



db.Users.Attach(LoggedUser);


Is it legit or this is not how we solve this problem. Any advice will be greatly appreciated



Added as requested:



StackTrace:




ex.StackTrace " at
System.Data.Entity.Core.Objects.ObjectContext.get_Connection()rn

at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption)rn at
System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption
mergeOption)rn at
System.Data.Entity.Core.Objects.DataClasses.EntityReference
1.Load(MergeOption
mergeOption)rn at
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()rn
at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem
propertyValue, String relationshipName, String targetRoleName, Boolean
mustBeNull, Object wrapperObject)rn at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.b__2(TProxy
proxy, TItem item)rn at
System.Data.Entity.DynamicProxies.ApplicationUser_3D8410FBA1701532D53558B4E07B366CC45F4901DA609FCE10D652D704EEDD3C.get_CarGame()rn
at PersonalProject.Controllers.MainPageController.GetUserInfo() in
C:UsersJackDesktopPostPersonalProjectPersonalProjectPersonalProjectControllersMainPageController.cs:line
32" string











share|improve this question

























  • Show full stack trace, please. Attaching LoggedUser to another context looks pointless.

    – Dennis
    Nov 23 '18 at 9:20











  • I added the stack trace. And what do you mean by pointless? It works if I add it. Otherwise is doesn't.

    – Happy Coconut
    Nov 23 '18 at 9:55
















0















This question has been asked a lot of times. I think I solved my problem but since I am a beginner and still learning I need your reassurance.



I made a Extension method for the Logged In User But when I use it in my Controller it gives me the error in title.




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




So I searched and experimented and adding this line of code
in the controller solved my problem.



db.Users.Attach(LoggedUser);


However I am not sure if my answer is correct, since a lot of answers about this question were to disable the Lazy Loading but I didn't end up using it.



Something like this.



public class MyDbContext : DbContext
{
public MyDbContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}


Here is my Extension method:



 public static ApplicationUser GetLoggedInUserInDB(this System.Security.Principal.IPrincipal _User)
{
using (var db = new ApplicationDbContext())
{
string userId = _User.Identity.GetUserId();
var LoggedUser = db.Users.Find(userId);
return LoggedUser;
}
}


My Controller:



public class MainPageController : ApiController
{
[Route("Personal_Project/Main_Page_Personal_Project/UserUnfo")]
[ResponseType(typeof(string))]
[Authorize]
public IHttpActionResult GetUserInfo()
{
using (var db = new ApplicationDbContext())
{
var LoggedUser = User.GetLoggedInUserInDB();
//db.Users.Attach(LoggedUser); // This is what I added to solve my problem.
return Ok(new UserInfoModel
{
Name = LoggedUser.UserName,
Reputation = LoggedUser.Reputation,
UserLevel = LoggedUser.UserLevel
});
}
}
}


So is 'My' solution here good? Just adding:



db.Users.Attach(LoggedUser);


Is it legit or this is not how we solve this problem. Any advice will be greatly appreciated



Added as requested:



StackTrace:




ex.StackTrace " at
System.Data.Entity.Core.Objects.ObjectContext.get_Connection()rn

at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption)rn at
System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption
mergeOption)rn at
System.Data.Entity.Core.Objects.DataClasses.EntityReference
1.Load(MergeOption
mergeOption)rn at
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()rn
at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem
propertyValue, String relationshipName, String targetRoleName, Boolean
mustBeNull, Object wrapperObject)rn at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.b__2(TProxy
proxy, TItem item)rn at
System.Data.Entity.DynamicProxies.ApplicationUser_3D8410FBA1701532D53558B4E07B366CC45F4901DA609FCE10D652D704EEDD3C.get_CarGame()rn
at PersonalProject.Controllers.MainPageController.GetUserInfo() in
C:UsersJackDesktopPostPersonalProjectPersonalProjectPersonalProjectControllersMainPageController.cs:line
32" string











share|improve this question

























  • Show full stack trace, please. Attaching LoggedUser to another context looks pointless.

    – Dennis
    Nov 23 '18 at 9:20











  • I added the stack trace. And what do you mean by pointless? It works if I add it. Otherwise is doesn't.

    – Happy Coconut
    Nov 23 '18 at 9:55














0












0








0


0






This question has been asked a lot of times. I think I solved my problem but since I am a beginner and still learning I need your reassurance.



I made a Extension method for the Logged In User But when I use it in my Controller it gives me the error in title.




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




So I searched and experimented and adding this line of code
in the controller solved my problem.



db.Users.Attach(LoggedUser);


However I am not sure if my answer is correct, since a lot of answers about this question were to disable the Lazy Loading but I didn't end up using it.



Something like this.



public class MyDbContext : DbContext
{
public MyDbContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}


Here is my Extension method:



 public static ApplicationUser GetLoggedInUserInDB(this System.Security.Principal.IPrincipal _User)
{
using (var db = new ApplicationDbContext())
{
string userId = _User.Identity.GetUserId();
var LoggedUser = db.Users.Find(userId);
return LoggedUser;
}
}


My Controller:



public class MainPageController : ApiController
{
[Route("Personal_Project/Main_Page_Personal_Project/UserUnfo")]
[ResponseType(typeof(string))]
[Authorize]
public IHttpActionResult GetUserInfo()
{
using (var db = new ApplicationDbContext())
{
var LoggedUser = User.GetLoggedInUserInDB();
//db.Users.Attach(LoggedUser); // This is what I added to solve my problem.
return Ok(new UserInfoModel
{
Name = LoggedUser.UserName,
Reputation = LoggedUser.Reputation,
UserLevel = LoggedUser.UserLevel
});
}
}
}


So is 'My' solution here good? Just adding:



db.Users.Attach(LoggedUser);


Is it legit or this is not how we solve this problem. Any advice will be greatly appreciated



Added as requested:



StackTrace:




ex.StackTrace " at
System.Data.Entity.Core.Objects.ObjectContext.get_Connection()rn

at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption)rn at
System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption
mergeOption)rn at
System.Data.Entity.Core.Objects.DataClasses.EntityReference
1.Load(MergeOption
mergeOption)rn at
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()rn
at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem
propertyValue, String relationshipName, String targetRoleName, Boolean
mustBeNull, Object wrapperObject)rn at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.b__2(TProxy
proxy, TItem item)rn at
System.Data.Entity.DynamicProxies.ApplicationUser_3D8410FBA1701532D53558B4E07B366CC45F4901DA609FCE10D652D704EEDD3C.get_CarGame()rn
at PersonalProject.Controllers.MainPageController.GetUserInfo() in
C:UsersJackDesktopPostPersonalProjectPersonalProjectPersonalProjectControllersMainPageController.cs:line
32" string











share|improve this question
















This question has been asked a lot of times. I think I solved my problem but since I am a beginner and still learning I need your reassurance.



I made a Extension method for the Logged In User But when I use it in my Controller it gives me the error in title.




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




So I searched and experimented and adding this line of code
in the controller solved my problem.



db.Users.Attach(LoggedUser);


However I am not sure if my answer is correct, since a lot of answers about this question were to disable the Lazy Loading but I didn't end up using it.



Something like this.



public class MyDbContext : DbContext
{
public MyDbContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}


Here is my Extension method:



 public static ApplicationUser GetLoggedInUserInDB(this System.Security.Principal.IPrincipal _User)
{
using (var db = new ApplicationDbContext())
{
string userId = _User.Identity.GetUserId();
var LoggedUser = db.Users.Find(userId);
return LoggedUser;
}
}


My Controller:



public class MainPageController : ApiController
{
[Route("Personal_Project/Main_Page_Personal_Project/UserUnfo")]
[ResponseType(typeof(string))]
[Authorize]
public IHttpActionResult GetUserInfo()
{
using (var db = new ApplicationDbContext())
{
var LoggedUser = User.GetLoggedInUserInDB();
//db.Users.Attach(LoggedUser); // This is what I added to solve my problem.
return Ok(new UserInfoModel
{
Name = LoggedUser.UserName,
Reputation = LoggedUser.Reputation,
UserLevel = LoggedUser.UserLevel
});
}
}
}


So is 'My' solution here good? Just adding:



db.Users.Attach(LoggedUser);


Is it legit or this is not how we solve this problem. Any advice will be greatly appreciated



Added as requested:



StackTrace:




ex.StackTrace " at
System.Data.Entity.Core.Objects.ObjectContext.get_Connection()rn

at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption)rn at
System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption
mergeOption)rn at
System.Data.Entity.Core.Objects.DataClasses.EntityReference
1.Load(MergeOption
mergeOption)rn at
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()rn
at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem
propertyValue, String relationshipName, String targetRoleName, Boolean
mustBeNull, Object wrapperObject)rn at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.b__2(TProxy
proxy, TItem item)rn at
System.Data.Entity.DynamicProxies.ApplicationUser_3D8410FBA1701532D53558B4E07B366CC45F4901DA609FCE10D652D704EEDD3C.get_CarGame()rn
at PersonalProject.Controllers.MainPageController.GetUserInfo() in
C:UsersJackDesktopPostPersonalProjectPersonalProjectPersonalProjectControllersMainPageController.cs:line
32" string








c# asp.net asp.net-web-api2 asp.net-identity






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 10:44









Dennis

29.5k760110




29.5k760110










asked Nov 23 '18 at 9:08









Happy CoconutHappy Coconut

229414




229414













  • Show full stack trace, please. Attaching LoggedUser to another context looks pointless.

    – Dennis
    Nov 23 '18 at 9:20











  • I added the stack trace. And what do you mean by pointless? It works if I add it. Otherwise is doesn't.

    – Happy Coconut
    Nov 23 '18 at 9:55



















  • Show full stack trace, please. Attaching LoggedUser to another context looks pointless.

    – Dennis
    Nov 23 '18 at 9:20











  • I added the stack trace. And what do you mean by pointless? It works if I add it. Otherwise is doesn't.

    – Happy Coconut
    Nov 23 '18 at 9:55

















Show full stack trace, please. Attaching LoggedUser to another context looks pointless.

– Dennis
Nov 23 '18 at 9:20





Show full stack trace, please. Attaching LoggedUser to another context looks pointless.

– Dennis
Nov 23 '18 at 9:20













I added the stack trace. And what do you mean by pointless? It works if I add it. Otherwise is doesn't.

– Happy Coconut
Nov 23 '18 at 9:55





I added the stack trace. And what do you mean by pointless? It works if I add it. Otherwise is doesn't.

– Happy Coconut
Nov 23 '18 at 9:55












1 Answer
1






active

oldest

votes


















1














You're getting exception because of this: get_CarGame().



Code inside original post doesn't match your actual code.



Somewhere inside actual MainPageController.GetUserInfo you're trying to read ApplicationUser.CarGame. And yes, this is lazy loading issue.



GetLoggedInUserInDB returns instance of proxy class, derived from ApplicationUser, and disposes original context. When GetUserInfo tries to get CarGame property value, proxy attempts to read it from database, using disposed context. As a result, exception is being thrown.



If you really need CarGame inside UserInfoModel:




  • either turn off lazy loading as shown above, and use eager loading;

  • use projection (that is, Select) to retrieve user info as UserInfoModel in place. In this case there is no need in GetLoggedInUserInDB method at all.


Anyway, attaching LoggedUser to another context is not a way to go.






share|improve this answer
























  • Thanks a lot for the feedback and your time.

    – Happy Coconut
    Nov 23 '18 at 11:03











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53443575%2fthe-objectcontext-instance-has-been-disposed-and-can-no-longer-be-used-for-oper%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You're getting exception because of this: get_CarGame().



Code inside original post doesn't match your actual code.



Somewhere inside actual MainPageController.GetUserInfo you're trying to read ApplicationUser.CarGame. And yes, this is lazy loading issue.



GetLoggedInUserInDB returns instance of proxy class, derived from ApplicationUser, and disposes original context. When GetUserInfo tries to get CarGame property value, proxy attempts to read it from database, using disposed context. As a result, exception is being thrown.



If you really need CarGame inside UserInfoModel:




  • either turn off lazy loading as shown above, and use eager loading;

  • use projection (that is, Select) to retrieve user info as UserInfoModel in place. In this case there is no need in GetLoggedInUserInDB method at all.


Anyway, attaching LoggedUser to another context is not a way to go.






share|improve this answer
























  • Thanks a lot for the feedback and your time.

    – Happy Coconut
    Nov 23 '18 at 11:03
















1














You're getting exception because of this: get_CarGame().



Code inside original post doesn't match your actual code.



Somewhere inside actual MainPageController.GetUserInfo you're trying to read ApplicationUser.CarGame. And yes, this is lazy loading issue.



GetLoggedInUserInDB returns instance of proxy class, derived from ApplicationUser, and disposes original context. When GetUserInfo tries to get CarGame property value, proxy attempts to read it from database, using disposed context. As a result, exception is being thrown.



If you really need CarGame inside UserInfoModel:




  • either turn off lazy loading as shown above, and use eager loading;

  • use projection (that is, Select) to retrieve user info as UserInfoModel in place. In this case there is no need in GetLoggedInUserInDB method at all.


Anyway, attaching LoggedUser to another context is not a way to go.






share|improve this answer
























  • Thanks a lot for the feedback and your time.

    – Happy Coconut
    Nov 23 '18 at 11:03














1












1








1







You're getting exception because of this: get_CarGame().



Code inside original post doesn't match your actual code.



Somewhere inside actual MainPageController.GetUserInfo you're trying to read ApplicationUser.CarGame. And yes, this is lazy loading issue.



GetLoggedInUserInDB returns instance of proxy class, derived from ApplicationUser, and disposes original context. When GetUserInfo tries to get CarGame property value, proxy attempts to read it from database, using disposed context. As a result, exception is being thrown.



If you really need CarGame inside UserInfoModel:




  • either turn off lazy loading as shown above, and use eager loading;

  • use projection (that is, Select) to retrieve user info as UserInfoModel in place. In this case there is no need in GetLoggedInUserInDB method at all.


Anyway, attaching LoggedUser to another context is not a way to go.






share|improve this answer













You're getting exception because of this: get_CarGame().



Code inside original post doesn't match your actual code.



Somewhere inside actual MainPageController.GetUserInfo you're trying to read ApplicationUser.CarGame. And yes, this is lazy loading issue.



GetLoggedInUserInDB returns instance of proxy class, derived from ApplicationUser, and disposes original context. When GetUserInfo tries to get CarGame property value, proxy attempts to read it from database, using disposed context. As a result, exception is being thrown.



If you really need CarGame inside UserInfoModel:




  • either turn off lazy loading as shown above, and use eager loading;

  • use projection (that is, Select) to retrieve user info as UserInfoModel in place. In this case there is no need in GetLoggedInUserInDB method at all.


Anyway, attaching LoggedUser to another context is not a way to go.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 23 '18 at 10:58









DennisDennis

29.5k760110




29.5k760110













  • Thanks a lot for the feedback and your time.

    – Happy Coconut
    Nov 23 '18 at 11:03



















  • Thanks a lot for the feedback and your time.

    – Happy Coconut
    Nov 23 '18 at 11:03

















Thanks a lot for the feedback and your time.

– Happy Coconut
Nov 23 '18 at 11:03





Thanks a lot for the feedback and your time.

– Happy Coconut
Nov 23 '18 at 11:03


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53443575%2fthe-objectcontext-instance-has-been-disposed-and-can-no-longer-be-used-for-oper%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'