c# - 使用 Lazyloading,如何在使用新的 DbContext 处理完其 DBContext 后加载相关对象?
问题描述
我有一个通用方法,用于从数据库中提取实体。
在这个通用方法中,我使用 IDbContextFactory 来获取我可以查询的 DbContext 对象。
public virtual List<T> GetTableRecordsByPartialInstance<T>(T whereObject) where T : class, ITable
{
using (SqlDboDbContext cntx = _DboContextFactory.CreateDbContext())
{
string tableName = cntx.Model.FindEntityType(typeof(T)).GetTableName();
string query;
List<SqlParameter> parameters;
GetQuery_NotNullWhereJoinWithAnd(whereObject, tableName, out query, out parameters);
IQueryable<T> queryObj = null;
try
{
queryObj = cntx.Set<T>().FromSqlRaw(query, parameters.ToArray());
return queryObj.ToList();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
string strQuery = "";
strQuery = queryObj.ToQueryString();
throw;
}
}
}
这适用于不相关但我收到问题/警告的对象
System.Reflection.TargetInvocationException
Inner Exception 1:
InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.LazyLoadOnDisposedContextWarning': An attempt was made to lazy-load navigation 'PartyProfile.PartyProxy' after the associated DbContext was disposed.
当我尝试访问引用相关数据的模型中的数据时。
return typeof(TT).GetProperties().All(x => SomeMethod(x.GetValue(val)));
假设我发现了这个错误,我将如何将一个新的 DbContext 链接到这个 Lazy Loader 以便我可以获取数据?
有没有办法检查一个属性以提前知道我需要在尝试访问该值之前生成/链接一个新的 DbContext 吗?
解决方案
我将如何将新的 DbContext 链接到这个 Lazy Loader 以便我可以获取数据?
你不能。延迟加载代理绑定到单个 DbContext 实例。using
如果您想使用延迟加载,您应该为 DbContext 找到比块更好的生命周期。
如果需要,您还可以将实体附加到稍后的 DbContext 并显式加载相关实体。
推荐阅读
- phpexcel - Yii2 Kartik 导出带有子标题
- mysql - 如何在mysql中将别名设置为整数
- r - 查找矩阵或数据框的行中位数(样本中位数)
- javascript - Javascript - 确定数组是否应设置索引、添加新索引或将现有索引设置为 0
- python - 我无法使用 pyinstaller 将我的 python 文件转换为 exe
- android - 将 Firebase MLKit 边界框坐标转换为屏幕视图坐标
- python-3.x - 搜索功能太慢recordclass python优化
- python - 哪个更快?`list.pop(0)` vs `del list[0]`?
- google-maps - Google Address Api 未在 IE9 中显示搜索结果,但数据被填充到地址字段
- python - Python中的BST(二叉搜索树)Testdome