gpt4 book ai didi

c# - 如何检查我的实体对象是否延迟加载?

转载 作者:行者123 更新时间:2023-12-04 12:59:40 25 4
gpt4 key购买 nike

我有两个具有一对多关系的实体类。

public class Call : IEntity
{
public int Id { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}

public class User : IEntity
{
public int Id { get; set; }

public string Username { get; set; }
public virtual ICollection<Call> Calls { get; set; }
}

我有一个用于 Web 层上的“调用”操作的 View 模型。
public class CallVm : IViewModel
{
public string Id { get; set; }
public string UserFullname { get; set; }
}

我使用一种方法将我的“Call”对象转换为“CallVm”对象。
该方法简述如下。
public CallVm MapCallVm(Call call)
{
return call == null ? null : new CallVm { Id = call.Id, UserFullname = call.User?.Fullname };
}

当我从数据库中读取“Call”实体时,有时会包含“User”,有时不包含。当我不包含它时,Call 对象中没有 User 属性定义,因为它是延迟加载。因此,我在 MapCallVm 方法中收到以下错误。

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.



有没有办法检查这个?我只想分配 UserFullname = call.User?.Fullname当有急切负载时。
我能想到的唯一解决方案是使用 try-catch 进行控制。有不同的解决方案吗?

最佳答案

您可以使用 DbReferenceEntry.IsLoaded属性(property)。

Gets or sets a value indicating whether the entity has been loaded from the database.


if (_dbContext.Entry(Call).Reference(e => e.User).IsLoaded)

更新

如果您在没有 dbContext 的情况下获得值(value),您应该强制查询 Eager loading反而。

阅读以下帖子以获得更好的理解。

Should we disable lazy loading of Entity Framework in web apps?

关于c# - 如何检查我的实体对象是否延迟加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60069695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com