Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么在显式地将lazy loaded属性设置为null时会得到ObjectDisposedException?_C#_Entity Framework_Entity Framework 6 - Fatal编程技术网

C# 为什么在显式地将lazy loaded属性设置为null时会得到ObjectDisposedException?

C# 为什么在显式地将lazy loaded属性设置为null时会得到ObjectDisposedException?,c#,entity-framework,entity-framework-6,C#,Entity Framework,Entity Framework 6,当显式设置延迟加载的属性时,我不应该避免这个特殊的问题吗? 还值得一提的是,调试时,行config.Farm=null有时会失败。场保留为其先前指定的代理值。此外,有时一切都是例外的(通常如果我调试缓慢) 我错过了什么 有关班级: [Table("statusconfig")] public class StatusConfig { [Key] public long Id { get; set; } public long Farm_Id { g

当显式设置延迟加载的属性时,我不应该避免这个特殊的问题吗? 还值得一提的是,调试时,行
config.Farm=null
有时会失败。场保留为其先前指定的代理值。此外,有时一切都是例外的(通常如果我调试缓慢)

我错过了什么

有关班级:

[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 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;
            }
        }
我的方法用于访问数据库的方法:

public IQueryable<T> Get(IUnitOfWork unitOfWork)
{
    return unitOfWork.GetDbSet<T>();
}
publicIQueryable获取(IUnitOfWork unitOfWork)
{
返回unitOfWork.GetDbSet();
}

public DbSet GetDbSet(),其中T:class
{
返回_centralDbContext.Set();
}
异常消息:

{
  "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)"
    }
  }
}
{
“消息”:“发生错误。”,
“ExceptionMessage”:“ObjectContent'1'类型未能序列化内容类型'application/json;charset=utf-8'的响应正文。”,
“异常类型”:“System.InvalidOperationException”,
“StackTrace”:空,
“内部异常”:{
“消息”:“发生错误。”,
“ExceptionMessage”:“从'System.Data.Entity.DynamicProxies.StatusConfig'上的'Farm'获取值时出错。\u C1AB21464AB7963C159323DD5304227C407A8689577431C20C5771DD7B5CA55”,
“ExceptionType”:“Newtonsoft.Json.JsonSerializationException”,
“StackTrace”:“vid Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(对象目标)\r\n vid Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter编写器、对象值、JsonContainerContract、JsonProperty成员、JsonProperty属性、JsonContract和memberContract、对象和成员值)\r\n请参阅Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter编写器,对象值,JsonObjectContract合同,JsonProperty成员,JsonContainerContract集合合同,JsonProperty容器属性)\r\n请参阅Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter编写器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r\n请参阅Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter JsonWriter,对象值,类型objectType)\r\n请参阅Newtonsoft.Json.JsonSerializer.serializer\n(JsonWriter JsonWriter,对象值,类型objectType)\r\n查看Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter JsonWriter,对象值)\r\n查看System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型,对象值,流writeStream writeStream,Encoding-effectiveEncoding)\r\n vid System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(类型、对象值、流writeStream、编码有效编码)\r\n vid System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型、对象值、流writeStream、HttpContent)\r\n vid System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(类型类型、对象值、流writeStream、HttpContent内容、TransportContext TransportContext、CancellationToken CancellationToken)\r\n---荡妇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.taskaiter\n vider\r\n vid System.Web.Http.WebHost.HttpControllerHandler.d_u1b.MoveNext()“,
“内部异常”:{
“消息”:“发生错误。”,
“ExceptionMessage”:“ObjectContext实例已被释放,不能再用于需要连接的操作。”,
“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.Object.DataClass.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_uudisplayClass7`2.b_uuu2(TProxy代理,TItem项)\r\n vid System.Data.Entity.DynamicProxies.StatusConfig_C1AB21464AB7963C159323DD5304227C407A8689577431C20771DD7B5CA55.GetFarm()\r\n vid GetFarm(对象)\r\n vid Newtonsoft.Json.Serialization.dynamicValue Provider.GetValue(目标)
}
}
}

我通过使用
Include
急切地加载关系场解决了这个问题。在此之后,我可以毫无问题地选择将其包含在响应中,或者像我以前尝试的那样将其设置为null。我仍然不明白为什么我以前的方法没有按预期工作

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

很抱歉@Jean.R,但是这个解决方案是如何解决这个问题的?这不是两个不同的问题吗?循环引用处理和延迟加载属性的处理?抱歉,与另一个主题混淆了,绝对无关!
var config = _statusConfigRepository.Get(unitOfWork).Include(statusConfig => statusConfig.Farm)
                    .FirstOrDefault(statusConfig => statusConfig.Farm_Id == farmId);