2016-08-24 61 views
1

當明確設置延遲加載的屬性時,我不應該避免這個特殊問題嗎? 另外值得一提的是,在調試時,行config.Farm = null有時會失敗。農場保留它以前分配的代理值。另外,有時候所有的東西都可以作爲例外(通常如果我慢慢調試)。爲什麼我在將lazy-loaded屬性設置爲null時顯示ObjectDisposedException?

我缺少什麼?

有問題的類:

[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 
} 

我的方法:

public IQueryable<T> Get(IUnitOfWork unitOfWork) 
{ 
    return unitOfWork.GetDbSet<T>(); 
} 

public DbSet<T> GetDbSet<T>() where T : class 
{ 
    return _centralDbContext.Set<T>(); 
} 

public StatusConfig GetOrCreate(long farmId) 
     { 
      using (var unitOfWork = _unitOfWorkFactory.Create()) 
      { 
       var config = 
        _statusConfigRepository.Get(unitOfWork) 
         .FirstOrDefault(statusConfig => 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; 
      } 
     } 

使用我的方法來訪問數據庫的方法

異常消息:

{ 
    "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& memberContract, Object& 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.<WriteBufferedResponseContentAsync>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.<>c__DisplayClass7`2.<GetInterceptorDelegate>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)" 
    } 
    } 
} 
+0

對不起@ Jean.R,但該解決方案如何解決這個問題?循環引用處理和放置延遲加載屬性不是兩個不同的問題嗎? –

+0

對不起,混淆了另一個話題,絕對不相干! –

回答

1

我排序通過使用Include到熱切加載關係農場解決了這個。在此之後,我可以沒有任何問題選擇將其包含在響應中,或者將它設置爲null,因爲我之前嘗試過。仍然不明白爲什麼我以前的方法沒有按預期工作。

var config = _statusConfigRepository.Get(unitOfWork).Include(statusConfig => statusConfig.Farm) 
        .FirstOrDefault(statusConfig => statusConfig.Farm_Id == farmId); 
相關問題