Why am I getting ObjectDisposedException when setting lazy-loaded property to null explicitly?
<p>Shouldn't I be avoiding this particular problem when explicitly setting the property that is lazy loaded?
Also worth mentioning is that when debugging, the line <code>config.Farm = null</code> sometimes fails. Farm stays as the proxy value it's previously assigned. Also, sometimes everything works as excepted (usually if i debug slowly). </p>

<p>What am I missing?</p>

<p>The class in question:</p>

<pre><code>[Table("statusconfig")]
public class StatusConfig
{
        [Key]
        public long Id { get; set; }
        public long Farm_Id { get; set; }
        [ForeignKey("Farm_Id")]
        public virtual Farm Farm { get; set; }

        // And other columns
} 
</code></pre>

<p>My method:</p>

<pre><code>public StatusConfig GetOrCreate(long farmId)
        {
            using (var unitOfWork = _unitOfWorkFactory.Create())
            {
                var config =
                    _statusConfigRepository.Get(unitOfWork)
                        .FirstOrDefault(statusConfig =&gt; statusConfig.Farm_Id == farmId);
                if (config != null)
                {
                    config.Farm = null;
                    return config;
                }
                config = new StatusConfig
                {
                    LastUpdated = DateTime.UtcNow,
                    Farm_Id = farmId
                };
                _statusConfigRepository.Add(unitOfWork, config);
                unitOfWork.Commit();
                return config;
            }
        }
</code></pre>

<p>The methods used by my method to access the database:</p>

<pre><code>public IQueryable&lt;T&gt; Get(IUnitOfWork unitOfWork)
{
    return unitOfWork.GetDbSet&lt;T&gt;();
}
</code></pre>

<hr>

<pre><code>public DbSet&lt;T&gt; GetDbSet&lt;T&gt;() where T : class
{
    return _centralDbContext.Set&lt;T&gt;();
}
</code></pre>

<p>Exception message:</p>

<pre><code>{
  "Message": "An error has occurred.",
  "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": null,
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "Error getting value from 'Farm' on 'System.Data.Entity.DynamicProxies.StatusConfig_C1AB21464AB7963C159323DD5304227C407A8689577431C20C5771DDE7B5CA55'.",
    "ExceptionType": "Newtonsoft.Json.JsonSerializationException",
    "StackTrace": "   vid Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n   vid Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract&amp; memberContract, Object&amp; memberValue)\r\n   vid Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   vid Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   vid Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   vid Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   vid Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)\r\n   vid System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   vid System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   vid System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n   vid System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- Slut på stackspårningen från föregående plats där ett undantag utlöstes ---\r\n   vid System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   vid System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   vid System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   vid System.Web.Http.WebHost.HttpControllerHandler.&lt;WriteBufferedResponseContentAsync&gt;d__1b.MoveNext()",
    "InnerException": {
      "Message": "An error has occurred.",
      "ExceptionMessage": "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.",
      "ExceptionType": "System.ObjectDisposedException",
      "StackTrace": "   vid System.Data.Entity.Core.Objects.ObjectContext.get_Connection()\r\n   vid System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n   vid System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n   vid System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption)\r\n   vid System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n   vid System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n   vid System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.&lt;&gt;c__DisplayClass7`2.&lt;GetInterceptorDelegate&gt;b__2(TProxy proxy, TItem item)\r\n   vid System.Data.Entity.DynamicProxies.StatusConfig_C1AB21464AB7963C159323DD5304227C407A8689577431C20C5771DDE7B5CA55.get_Farm()\r\n   vid GetFarm(Object )\r\n   vid Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
    }
  }
}
</code></pre>