【发布时间】:2015-07-03 17:54:55
【问题描述】:
我使用的是实体框架 6,首先是 DBcontext 数据库。 当我有一个代理对象并且我想获取 DBContext 时,我遇到了一些情况。 我正在使用此代码:
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
namespace Sample
{
public class MyDbContext : DbContext
{
private static readonly Dictionary<ObjectContext, MyDbContext> contexts =
new Dictionary<ObjectContext, MyDbContext>();
public static MyDbContext FromObjectContext(ObjectContext context)
{
lock (contexts)
{
if (contexts.ContainsKey(context))
return contexts[context];
return null;
}
}
public static MyDbContext FromObject(object obj)
{
var field = obj.GetType().GetField("_entityWrapper");
var wrapper = field.GetValue(obj);
var property = wrapper.GetType().GetProperty("Context");
var context = (ObjectContext)property.GetValue(wrapper, null);
return FromObjectContext(context);
}
public MyDbContext()
{
lock (contexts)
contexts[((IObjectContextAdapter)this).ObjectContext] = this;
}
protected override void Dispose(bool disposing)
{
lock (contexts)
contexts.Remove(((IObjectContextAdapter)this).ObjectContext);
base.Dispose(disposing);
}
}
}
现在,通过这段代码,我可以使用以下代码获取 DBContext:
var ctx = MyDataContext.FromObject(MyObj1);
除一种情况外,此代码均有效:
如果我添加一个新对象并调用 SaveChanges,然后在尝试获取该对象后获取 DbContext,我会收到错误消息。就行了:
Dim wrapper = field.GetValue(obj)
错误:
An unhandled exception of type 'System.NullReferenceException' occurred in myprog.exe
Additional information: Object reference not set to an instance of an object.
我还发现在这种情况下,这一行什么也不返回:
var field = obj.GetType().GetField("_entityWrapper");
我能做什么? 谢谢!
【问题讨论】:
标签: entity-framework