将延迟加载的属性显式设置为null时,为什么会出现ObjectDisposedException?

尤西夫·图玛(Yousif Touma)

当显式设置延迟加载的属性时,我是否应该避免这个特殊的问题?还值得一提的是,在调试时,该行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>();
}

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

异常消息:

{
  "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)"
    }
  }
}
尤西夫·图玛(Yousif Touma)

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

将值设置为结构中的值时,为什么会出现“无法分配”错误?

来自分类Dev

尝试在评分栏中将值设置为“ rating”时,为什么会出现空指针异常?

来自分类Dev

为什么在设置背景图像时 background-image 属性需要显式指定 url()

来自分类Dev

加载fxml时为什么会出现stackoverflow?

来自分类Dev

在 SLL 中,当其原始节点属性默认设置为 None 时,为什么我们显式覆盖指向 None 的下一个指针?

来自分类Dev

使用虚拟延迟加载时出现 EF ObjectDisposedException

来自分类Dev

为什么显式声明的参考返回值会出现可空性警告?

来自分类Dev

尝试启动连接时为什么会出现NULL?

来自分类Dev

当在SqlAlchemy中的列上有默认设置时,将列的值显式设置为NULL

来自分类Dev

为什么在BASH开始时不会出现一些变量回显

来自分类Dev

当我在index(_,offsetBy,limitedBy)函数中将offsetBy值设置为endIndex值时,为什么swift会出现错误?

来自分类Dev

为什么只向下滚动到底部时,我的网页会出现延迟?

来自分类Dev

Xamarin形式:将Focus设置为Entry控件时,出现System.ObjectDisposedException

来自分类Dev

为什么会出现此故障,为什么mysql设置为false?

来自分类Dev

为什么即使在将 mysql 添加到设置后运行 django 项目时也会出现此错误?

来自分类Dev

尝试在Colfusion中使用JavaScript将src属性添加到img标签时,为什么会出现错误?

来自分类Dev

不知道为什么在将 UILabel 设置为隐藏时出现错误 | 迅速

来自分类Javascript

为什么在使用useState时将初始加载状态设置为true?

来自分类Dev

休眠-为什么延迟加载String属性?

来自分类Dev

在Selenium WebDriver中,为什么我们需要在使用显式等待之前将隐式等待设置为0

来自分类Linux

在Anaconda环境中尝试在PyCharm中加载matplotlib时,为什么会出现错误列表?

来自分类Dev

当我尝试在 VueJS 中加载组件时,为什么会出现此错误?

来自分类Dev

为什么会出现错误:`加载共享库时出错:libmpich.so.3`?

来自分类Dev

为什么会出现此TypeError?“没有将模块隐式转换为整数”

来自分类Dev

为什么会出现TypeError:没有将符号隐式转换为Integer?

来自分类Java

在Java中为什么会出现此错误:“属性值必须为常数”?

来自分类Dev

尝试从数据库中回显值时,为什么会出现错误(通知:未定义的索引)?

来自分类Dev

为什么会出现错误“未捕获的TypeError:无法读取null的属性'classList'”?

来自分类Dev

为什么做突变时会出现“无法为不可为空的字段返回null”错误?

Related 相关文章

  1. 1

    将值设置为结构中的值时,为什么会出现“无法分配”错误?

  2. 2

    尝试在评分栏中将值设置为“ rating”时,为什么会出现空指针异常?

  3. 3

    为什么在设置背景图像时 background-image 属性需要显式指定 url()

  4. 4

    加载fxml时为什么会出现stackoverflow?

  5. 5

    在 SLL 中,当其原始节点属性默认设置为 None 时,为什么我们显式覆盖指向 None 的下一个指针?

  6. 6

    使用虚拟延迟加载时出现 EF ObjectDisposedException

  7. 7

    为什么显式声明的参考返回值会出现可空性警告?

  8. 8

    尝试启动连接时为什么会出现NULL?

  9. 9

    当在SqlAlchemy中的列上有默认设置时,将列的值显式设置为NULL

  10. 10

    为什么在BASH开始时不会出现一些变量回显

  11. 11

    当我在index(_,offsetBy,limitedBy)函数中将offsetBy值设置为endIndex值时,为什么swift会出现错误?

  12. 12

    为什么只向下滚动到底部时,我的网页会出现延迟?

  13. 13

    Xamarin形式:将Focus设置为Entry控件时,出现System.ObjectDisposedException

  14. 14

    为什么会出现此故障,为什么mysql设置为false?

  15. 15

    为什么即使在将 mysql 添加到设置后运行 django 项目时也会出现此错误?

  16. 16

    尝试在Colfusion中使用JavaScript将src属性添加到img标签时,为什么会出现错误?

  17. 17

    不知道为什么在将 UILabel 设置为隐藏时出现错误 | 迅速

  18. 18

    为什么在使用useState时将初始加载状态设置为true?

  19. 19

    休眠-为什么延迟加载String属性?

  20. 20

    在Selenium WebDriver中,为什么我们需要在使用显式等待之前将隐式等待设置为0

  21. 21

    在Anaconda环境中尝试在PyCharm中加载matplotlib时,为什么会出现错误列表?

  22. 22

    当我尝试在 VueJS 中加载组件时,为什么会出现此错误?

  23. 23

    为什么会出现错误:`加载共享库时出错:libmpich.so.3`?

  24. 24

    为什么会出现此TypeError?“没有将模块隐式转换为整数”

  25. 25

    为什么会出现TypeError:没有将符号隐式转换为Integer?

  26. 26

    在Java中为什么会出现此错误:“属性值必须为常数”?

  27. 27

    尝试从数据库中回显值时,为什么会出现错误(通知:未定义的索引)?

  28. 28

    为什么会出现错误“未捕获的TypeError:无法读取null的属性'classList'”?

  29. 29

    为什么做突变时会出现“无法为不可为空的字段返回null”错误?

热门标签

归档