我使用的是实体框架6,DBcontext Database First。当我有一个代理对象并且想要获取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");
我能做什么?非常感谢。
添加新对象时,新对象仍然是原始对象(而不是带有代理的对象(。您可以使用DbSet。创建而不是新建,这样您就已经有了一个带有代理的实体。