Entity Framework 6.1.3 when dbContext disposed detached objects are null Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Entity Framework vs LINQ to SQLEntity Framework - Detaching entities when ObjectContext disposed?Entity Framework Code First - No Detach() method on DbContextFastest Way of Inserting in Entity FrameworkEntity Framework TimeoutsEntity Framework and DbContext - Object TrackingDispose DbContext not dispose the ObjectContext entitiesEntity Framework 5 Updating a RecordDbContext discard changes without disposingDBContext disposing doesn't change the number of opened connections

Is it acceptable to use working hours to read general interest books?

Will I lose my paid in full property

Seek and ye shall find

What *exactly* is electrical current, voltage, and resistance?

I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?

How would I use different systems of magic when they are capable of the same effects?

How to avoid introduction cliches

Is Electric Central Heating worth it if using Solar Panels?

Can I criticise the more senior developers around me for not writing clean code?

Why didn't the Space Shuttle bounce back into space as many times as possible so as to lose a lot of kinetic energy up there?

Check if a string is entirely made of the same substring

Passing args from the bash script to the function in the script

Arriving in Atlanta after US Preclearance in Dublin. Will I go through TSA security in Atlanta to transfer to a connecting flight?

Is Bran literally the world's memory?

Does Feeblemind produce an ongoing magical effect that can be dispelled?

Would reducing the reference voltage of an ADC have any effect on accuracy?

Do I need to protect SFP ports and optics from dust/contaminants? If so, how?

Where did Arya get these scars?

Why does the Cisco show run command not show the full version, while the show version command does?

Retract an already submitted recommendation letter (written for an undergrad student)

"My boss was furious with me and I have been fired" vs. "My boss was furious with me and I was fired"

What is the term for a person whose job is to place products on shelves in stores?

How to open locks without disable device?

Multiple fireplaces in an apartment building?



Entity Framework 6.1.3 when dbContext disposed detached objects are null



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Entity Framework vs LINQ to SQLEntity Framework - Detaching entities when ObjectContext disposed?Entity Framework Code First - No Detach() method on DbContextFastest Way of Inserting in Entity FrameworkEntity Framework TimeoutsEntity Framework and DbContext - Object TrackingDispose DbContext not dispose the ObjectContext entitiesEntity Framework 5 Updating a RecordDbContext discard changes without disposingDBContext disposing doesn't change the number of opened connections



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















The below code uses DBContext, and at times I get Subject[] array being null and can only assume that detached objects on disposal of the context has an effect on these same objects making their references null out of the scope the above mentioned. That's when the subject[] array is returned to the caller. In the caller a reference to subjec[] at times returns null. Is this how it should be?



public Subject[] GetSubjectList()

using (var dbContext = new DataAccess.TeachersAssistantDbContext())

_unitOfWork.InitializeDbContext(dbContext);
return _unitOfWork._subjectRepository.GetAll();




I was expecting since the dbContext is disposed, the objects get detached, and still should exist within the calling code provided there is a reference to them. I am getting this error with Entity Framework 6.1.3










share|improve this question
























  • Couple of things to note. 1. I am not sure how your Unit Of Work object works but at least, you should get back a list of Subject entities before your DbContext gets disposed. 2. It is not a good idea to pass in a DbContext into your Unit Of Work that is going to get disposed later (especially if the Unit Of Work outlives it). 3. Your Subject entities should be fine outside the scope of a DbContext provided you don't call any properties that have Dynamic proxies loaded in them that will access the Db. As for why the Subject[] is sometimes null is not known to me yet.

    – Dandré
    Mar 9 at 6:39












  • Thanks Dandre, my Unit Of Work just composes Repositories that use the same DBContext that is why the dbcontext is injected into it. It baffles me that sometimes it works and other times it doesn't. It was working fine, and now I am consistently getting null exceptions within the calling code. Note also that I am not using the entities in updates but just querying their properties for app consumption. Nothing gets persisted after - of course, because the context has been disposed. So I am struggling understanding what was working before is failing now. And it has become consistent failures.

    – Martin Alex Okello
    Mar 9 at 8:09











  • could you post the code of the repository GetAll() function? And what does InitializeDbContext() do? The DbSet functions will not return null objects, unless you call FirstOrDefault()/SingleOrDefault() with reference types on an empty sequence.

    – DevilSuichiro
    Mar 9 at 8:26











  • @MartinAlexOkello, I think the main point I'm trying to make is that there may be a design flaw in your code and that is causing your code to misbehave. If I get a chance I will post some good articles that will explain what the best practices are for using EF, Repos, etc. But I would second DevilSuichiro about the specifics of your custom methods.

    – Dandré
    Mar 9 at 10:49












  • My reposiories inherit from Abstract Repository with this method in it. public T[] GetAll() try return DbContextTeachersAssistant.Set<T>().ToArray<T>(); catch return null;

    – Martin Alex Okello
    Mar 9 at 10:52


















-1















The below code uses DBContext, and at times I get Subject[] array being null and can only assume that detached objects on disposal of the context has an effect on these same objects making their references null out of the scope the above mentioned. That's when the subject[] array is returned to the caller. In the caller a reference to subjec[] at times returns null. Is this how it should be?



public Subject[] GetSubjectList()

using (var dbContext = new DataAccess.TeachersAssistantDbContext())

_unitOfWork.InitializeDbContext(dbContext);
return _unitOfWork._subjectRepository.GetAll();




I was expecting since the dbContext is disposed, the objects get detached, and still should exist within the calling code provided there is a reference to them. I am getting this error with Entity Framework 6.1.3










share|improve this question
























  • Couple of things to note. 1. I am not sure how your Unit Of Work object works but at least, you should get back a list of Subject entities before your DbContext gets disposed. 2. It is not a good idea to pass in a DbContext into your Unit Of Work that is going to get disposed later (especially if the Unit Of Work outlives it). 3. Your Subject entities should be fine outside the scope of a DbContext provided you don't call any properties that have Dynamic proxies loaded in them that will access the Db. As for why the Subject[] is sometimes null is not known to me yet.

    – Dandré
    Mar 9 at 6:39












  • Thanks Dandre, my Unit Of Work just composes Repositories that use the same DBContext that is why the dbcontext is injected into it. It baffles me that sometimes it works and other times it doesn't. It was working fine, and now I am consistently getting null exceptions within the calling code. Note also that I am not using the entities in updates but just querying their properties for app consumption. Nothing gets persisted after - of course, because the context has been disposed. So I am struggling understanding what was working before is failing now. And it has become consistent failures.

    – Martin Alex Okello
    Mar 9 at 8:09











  • could you post the code of the repository GetAll() function? And what does InitializeDbContext() do? The DbSet functions will not return null objects, unless you call FirstOrDefault()/SingleOrDefault() with reference types on an empty sequence.

    – DevilSuichiro
    Mar 9 at 8:26











  • @MartinAlexOkello, I think the main point I'm trying to make is that there may be a design flaw in your code and that is causing your code to misbehave. If I get a chance I will post some good articles that will explain what the best practices are for using EF, Repos, etc. But I would second DevilSuichiro about the specifics of your custom methods.

    – Dandré
    Mar 9 at 10:49












  • My reposiories inherit from Abstract Repository with this method in it. public T[] GetAll() try return DbContextTeachersAssistant.Set<T>().ToArray<T>(); catch return null;

    – Martin Alex Okello
    Mar 9 at 10:52














-1












-1








-1








The below code uses DBContext, and at times I get Subject[] array being null and can only assume that detached objects on disposal of the context has an effect on these same objects making their references null out of the scope the above mentioned. That's when the subject[] array is returned to the caller. In the caller a reference to subjec[] at times returns null. Is this how it should be?



public Subject[] GetSubjectList()

using (var dbContext = new DataAccess.TeachersAssistantDbContext())

_unitOfWork.InitializeDbContext(dbContext);
return _unitOfWork._subjectRepository.GetAll();




I was expecting since the dbContext is disposed, the objects get detached, and still should exist within the calling code provided there is a reference to them. I am getting this error with Entity Framework 6.1.3










share|improve this question
















The below code uses DBContext, and at times I get Subject[] array being null and can only assume that detached objects on disposal of the context has an effect on these same objects making their references null out of the scope the above mentioned. That's when the subject[] array is returned to the caller. In the caller a reference to subjec[] at times returns null. Is this how it should be?



public Subject[] GetSubjectList()

using (var dbContext = new DataAccess.TeachersAssistantDbContext())

_unitOfWork.InitializeDbContext(dbContext);
return _unitOfWork._subjectRepository.GetAll();




I was expecting since the dbContext is disposed, the objects get detached, and still should exist within the calling code provided there is a reference to them. I am getting this error with Entity Framework 6.1.3







c# entity-framework dbcontext unit-of-work






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 12:33









James Z

11.2k71936




11.2k71936










asked Mar 9 at 6:22









Martin Alex OkelloMartin Alex Okello

113




113












  • Couple of things to note. 1. I am not sure how your Unit Of Work object works but at least, you should get back a list of Subject entities before your DbContext gets disposed. 2. It is not a good idea to pass in a DbContext into your Unit Of Work that is going to get disposed later (especially if the Unit Of Work outlives it). 3. Your Subject entities should be fine outside the scope of a DbContext provided you don't call any properties that have Dynamic proxies loaded in them that will access the Db. As for why the Subject[] is sometimes null is not known to me yet.

    – Dandré
    Mar 9 at 6:39












  • Thanks Dandre, my Unit Of Work just composes Repositories that use the same DBContext that is why the dbcontext is injected into it. It baffles me that sometimes it works and other times it doesn't. It was working fine, and now I am consistently getting null exceptions within the calling code. Note also that I am not using the entities in updates but just querying their properties for app consumption. Nothing gets persisted after - of course, because the context has been disposed. So I am struggling understanding what was working before is failing now. And it has become consistent failures.

    – Martin Alex Okello
    Mar 9 at 8:09











  • could you post the code of the repository GetAll() function? And what does InitializeDbContext() do? The DbSet functions will not return null objects, unless you call FirstOrDefault()/SingleOrDefault() with reference types on an empty sequence.

    – DevilSuichiro
    Mar 9 at 8:26











  • @MartinAlexOkello, I think the main point I'm trying to make is that there may be a design flaw in your code and that is causing your code to misbehave. If I get a chance I will post some good articles that will explain what the best practices are for using EF, Repos, etc. But I would second DevilSuichiro about the specifics of your custom methods.

    – Dandré
    Mar 9 at 10:49












  • My reposiories inherit from Abstract Repository with this method in it. public T[] GetAll() try return DbContextTeachersAssistant.Set<T>().ToArray<T>(); catch return null;

    – Martin Alex Okello
    Mar 9 at 10:52


















  • Couple of things to note. 1. I am not sure how your Unit Of Work object works but at least, you should get back a list of Subject entities before your DbContext gets disposed. 2. It is not a good idea to pass in a DbContext into your Unit Of Work that is going to get disposed later (especially if the Unit Of Work outlives it). 3. Your Subject entities should be fine outside the scope of a DbContext provided you don't call any properties that have Dynamic proxies loaded in them that will access the Db. As for why the Subject[] is sometimes null is not known to me yet.

    – Dandré
    Mar 9 at 6:39












  • Thanks Dandre, my Unit Of Work just composes Repositories that use the same DBContext that is why the dbcontext is injected into it. It baffles me that sometimes it works and other times it doesn't. It was working fine, and now I am consistently getting null exceptions within the calling code. Note also that I am not using the entities in updates but just querying their properties for app consumption. Nothing gets persisted after - of course, because the context has been disposed. So I am struggling understanding what was working before is failing now. And it has become consistent failures.

    – Martin Alex Okello
    Mar 9 at 8:09











  • could you post the code of the repository GetAll() function? And what does InitializeDbContext() do? The DbSet functions will not return null objects, unless you call FirstOrDefault()/SingleOrDefault() with reference types on an empty sequence.

    – DevilSuichiro
    Mar 9 at 8:26











  • @MartinAlexOkello, I think the main point I'm trying to make is that there may be a design flaw in your code and that is causing your code to misbehave. If I get a chance I will post some good articles that will explain what the best practices are for using EF, Repos, etc. But I would second DevilSuichiro about the specifics of your custom methods.

    – Dandré
    Mar 9 at 10:49












  • My reposiories inherit from Abstract Repository with this method in it. public T[] GetAll() try return DbContextTeachersAssistant.Set<T>().ToArray<T>(); catch return null;

    – Martin Alex Okello
    Mar 9 at 10:52

















Couple of things to note. 1. I am not sure how your Unit Of Work object works but at least, you should get back a list of Subject entities before your DbContext gets disposed. 2. It is not a good idea to pass in a DbContext into your Unit Of Work that is going to get disposed later (especially if the Unit Of Work outlives it). 3. Your Subject entities should be fine outside the scope of a DbContext provided you don't call any properties that have Dynamic proxies loaded in them that will access the Db. As for why the Subject[] is sometimes null is not known to me yet.

– Dandré
Mar 9 at 6:39






Couple of things to note. 1. I am not sure how your Unit Of Work object works but at least, you should get back a list of Subject entities before your DbContext gets disposed. 2. It is not a good idea to pass in a DbContext into your Unit Of Work that is going to get disposed later (especially if the Unit Of Work outlives it). 3. Your Subject entities should be fine outside the scope of a DbContext provided you don't call any properties that have Dynamic proxies loaded in them that will access the Db. As for why the Subject[] is sometimes null is not known to me yet.

– Dandré
Mar 9 at 6:39














Thanks Dandre, my Unit Of Work just composes Repositories that use the same DBContext that is why the dbcontext is injected into it. It baffles me that sometimes it works and other times it doesn't. It was working fine, and now I am consistently getting null exceptions within the calling code. Note also that I am not using the entities in updates but just querying their properties for app consumption. Nothing gets persisted after - of course, because the context has been disposed. So I am struggling understanding what was working before is failing now. And it has become consistent failures.

– Martin Alex Okello
Mar 9 at 8:09





Thanks Dandre, my Unit Of Work just composes Repositories that use the same DBContext that is why the dbcontext is injected into it. It baffles me that sometimes it works and other times it doesn't. It was working fine, and now I am consistently getting null exceptions within the calling code. Note also that I am not using the entities in updates but just querying their properties for app consumption. Nothing gets persisted after - of course, because the context has been disposed. So I am struggling understanding what was working before is failing now. And it has become consistent failures.

– Martin Alex Okello
Mar 9 at 8:09













could you post the code of the repository GetAll() function? And what does InitializeDbContext() do? The DbSet functions will not return null objects, unless you call FirstOrDefault()/SingleOrDefault() with reference types on an empty sequence.

– DevilSuichiro
Mar 9 at 8:26





could you post the code of the repository GetAll() function? And what does InitializeDbContext() do? The DbSet functions will not return null objects, unless you call FirstOrDefault()/SingleOrDefault() with reference types on an empty sequence.

– DevilSuichiro
Mar 9 at 8:26













@MartinAlexOkello, I think the main point I'm trying to make is that there may be a design flaw in your code and that is causing your code to misbehave. If I get a chance I will post some good articles that will explain what the best practices are for using EF, Repos, etc. But I would second DevilSuichiro about the specifics of your custom methods.

– Dandré
Mar 9 at 10:49






@MartinAlexOkello, I think the main point I'm trying to make is that there may be a design flaw in your code and that is causing your code to misbehave. If I get a chance I will post some good articles that will explain what the best practices are for using EF, Repos, etc. But I would second DevilSuichiro about the specifics of your custom methods.

– Dandré
Mar 9 at 10:49














My reposiories inherit from Abstract Repository with this method in it. public T[] GetAll() try return DbContextTeachersAssistant.Set<T>().ToArray<T>(); catch return null;

– Martin Alex Okello
Mar 9 at 10:52






My reposiories inherit from Abstract Repository with this method in it. public T[] GetAll() try return DbContextTeachersAssistant.Set<T>().ToArray<T>(); catch return null;

– Martin Alex Okello
Mar 9 at 10:52













1 Answer
1






active

oldest

votes


















0














Sorry Chaps, I run migrations before, and looks like there was one pending migration that didn't run. I checked, and indeed there was an addition to to the Model, and an Exception was being thrown about migrations expected due to inconsistency between database and dbContext. I have ever since run the migrations and the problem has been resolved. Many thanks for you help though. Someone may end up in this awkward situation without realising the Model Entities changed and not all migrations were run.






share|improve this answer























  • I noticed that you have a try/catch around your Set<T>().ToArray() and if an exception was raised, it returns null. I would recommend that you don't swallow your exceptions like that, especially since it couldn't inform you of the EF error that you had because you didn't run any migrations. Rather let your exception trickle up and be handled in your error handling component / logging layer.

    – Dandré
    Mar 9 at 20:14











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%2f55074633%2fentity-framework-6-1-3-when-dbcontext-disposed-detached-objects-are-null%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









0














Sorry Chaps, I run migrations before, and looks like there was one pending migration that didn't run. I checked, and indeed there was an addition to to the Model, and an Exception was being thrown about migrations expected due to inconsistency between database and dbContext. I have ever since run the migrations and the problem has been resolved. Many thanks for you help though. Someone may end up in this awkward situation without realising the Model Entities changed and not all migrations were run.






share|improve this answer























  • I noticed that you have a try/catch around your Set<T>().ToArray() and if an exception was raised, it returns null. I would recommend that you don't swallow your exceptions like that, especially since it couldn't inform you of the EF error that you had because you didn't run any migrations. Rather let your exception trickle up and be handled in your error handling component / logging layer.

    – Dandré
    Mar 9 at 20:14















0














Sorry Chaps, I run migrations before, and looks like there was one pending migration that didn't run. I checked, and indeed there was an addition to to the Model, and an Exception was being thrown about migrations expected due to inconsistency between database and dbContext. I have ever since run the migrations and the problem has been resolved. Many thanks for you help though. Someone may end up in this awkward situation without realising the Model Entities changed and not all migrations were run.






share|improve this answer























  • I noticed that you have a try/catch around your Set<T>().ToArray() and if an exception was raised, it returns null. I would recommend that you don't swallow your exceptions like that, especially since it couldn't inform you of the EF error that you had because you didn't run any migrations. Rather let your exception trickle up and be handled in your error handling component / logging layer.

    – Dandré
    Mar 9 at 20:14













0












0








0







Sorry Chaps, I run migrations before, and looks like there was one pending migration that didn't run. I checked, and indeed there was an addition to to the Model, and an Exception was being thrown about migrations expected due to inconsistency between database and dbContext. I have ever since run the migrations and the problem has been resolved. Many thanks for you help though. Someone may end up in this awkward situation without realising the Model Entities changed and not all migrations were run.






share|improve this answer













Sorry Chaps, I run migrations before, and looks like there was one pending migration that didn't run. I checked, and indeed there was an addition to to the Model, and an Exception was being thrown about migrations expected due to inconsistency between database and dbContext. I have ever since run the migrations and the problem has been resolved. Many thanks for you help though. Someone may end up in this awkward situation without realising the Model Entities changed and not all migrations were run.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 9 at 11:21









Martin Alex OkelloMartin Alex Okello

113




113












  • I noticed that you have a try/catch around your Set<T>().ToArray() and if an exception was raised, it returns null. I would recommend that you don't swallow your exceptions like that, especially since it couldn't inform you of the EF error that you had because you didn't run any migrations. Rather let your exception trickle up and be handled in your error handling component / logging layer.

    – Dandré
    Mar 9 at 20:14

















  • I noticed that you have a try/catch around your Set<T>().ToArray() and if an exception was raised, it returns null. I would recommend that you don't swallow your exceptions like that, especially since it couldn't inform you of the EF error that you had because you didn't run any migrations. Rather let your exception trickle up and be handled in your error handling component / logging layer.

    – Dandré
    Mar 9 at 20:14
















I noticed that you have a try/catch around your Set<T>().ToArray() and if an exception was raised, it returns null. I would recommend that you don't swallow your exceptions like that, especially since it couldn't inform you of the EF error that you had because you didn't run any migrations. Rather let your exception trickle up and be handled in your error handling component / logging layer.

– Dandré
Mar 9 at 20:14





I noticed that you have a try/catch around your Set<T>().ToArray() and if an exception was raised, it returns null. I would recommend that you don't swallow your exceptions like that, especially since it couldn't inform you of the EF error that you had because you didn't run any migrations. Rather let your exception trickle up and be handled in your error handling component / logging layer.

– Dandré
Mar 9 at 20:14



















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%2f55074633%2fentity-framework-6-1-3-when-dbcontext-disposed-detached-objects-are-null%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

1928 у кіно

Захаров Федір Захарович

Ель Греко