【发布时间】:2021-10-10 14:41:39
【问题描述】:
我有一个通用方法,用于从数据库中提取实体。
在这个通用方法中,我使用 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?
【问题讨论】:
标签: c# entity-framework generics dbcontext