从实体获取的DbContext实体框架 [英] Get DbContext from Entity in Entity Framework
问题描述
我在Visual Studio中试图找出为什么试图保持变更时,一个实体的行为出现异常调试会话业务层深的地方。
这将真正有助于获得实体所属到的DbContext的引用,在调用堆栈这一点。
即。看到什么状态是这样的实体(不变,修改等)
所以我在寻找这样一个辅助方法:
VAR db_context = DbContextHelpers.GetDbContext(实体);
//之后,我可以做这样的事情
VAR状态= db_context.Entry(实体);
我可以在调试过程中使用这个东西,在立即窗口。
任何人有什么建议?
附加说明
的
实体必须知道的的DbContext
的地方,因为它是使用它的延迟加载导航属性?
公共静态的DbContext GetDbContextFromEntity(对象实体)
{
VAR object_context = GetObjectContextFromEntity(实体);
如果(object_context == NULL)
返回NULL;
返回新的DbContext(object_context,dbContextOwnsObjectContext:假);
}
私有静态ObjectContext的GetObjectContextFromEntity(对象实体)
{
VAR字段= entity.GetType()getfield命令(_ entityWrapper);
如果(场== NULL)
返回NULL;
VAR包装= field.GetValue(实体);
VAR财产= wrapper.GetType()的getProperty(上下文);
VAR上下文=(ObjectContext中)property.GetValue(包装,NULL);
返回语境;
}
I'm deep somewhere in the Business layer in a debugging session in Visual Studio trying to figure out why an Entity is behaving strangely when trying to persist the changes.
It would really be helpful to get a reference to the DbContext this Entity belongs to, at this point in the call stack.
I.e. to see what the state is of this Entity is (Unchanged, Modified, etc).
So I'm looking for a helper method like this:
var db_context = DbContextHelpers.GetDbContext(entity);
// after that I could do something like this
var state = db_context.Entry(entity);
I can use this stuff in the Immediate window during debugging.
Anyone any suggestions?
Extra notes
The Entity must be aware of the DbContext
somewhere, because it is using it for lazy loading navigation properties?
public static DbContext GetDbContextFromEntity(object entity)
{
var object_context = GetObjectContextFromEntity( entity );
if ( object_context == null )
return null;
return new DbContext( object_context, dbContextOwnsObjectContext: false );
}
private static ObjectContext GetObjectContextFromEntity(object entity)
{
var field = entity.GetType().GetField("_entityWrapper");
if ( field == null )
return null;
var wrapper = field.GetValue(entity);
var property = wrapper.GetType().GetProperty("Context");
var context = (ObjectContext)property.GetValue(wrapper, null);
return context;
}
这篇关于从实体获取的DbContext实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!