db.Entry().Entity 将始终返回一个 POCO,并且不会返回处理虚拟导航属性实现的代理对象:
var o = db.Entry(myPoco).Entity; // always returns a POCO
Find()
在调用或Where()
针对数据库上下文时,您通常会得到一个代理对象而不是 POCO 。但是,在对象首次添加到数据库的上下文中,这些方法将(出乎意料?)返回 POCO 而不是代理对象。您实际上必须离开上下文并打开一个新上下文才能获取代理:
// create a new POCO object, and connect to it to another object already in the DB
MyPoco myPoco = new MyPoco();
myPoco.MyOtherPocoId = myPoco2.MyOtherPocoId; // make reference to existing object
using (var db = new MyContext())
{
// Add myPoco to database.
db.MyPocos.Add(myPoco);
db.SaveChanges();
// One would think you get a proxy object here, but you don't: just a POCO
var test10 = db.MyPocos.Find(myPoco.Id); // returns a MyPoco
var test11 = db.MyPocos.Where(x => x.Id == myPoco.Id).First(); // returns a MyPoco
var test12 = db.Entry(myPoco).Entity; // returns a MyPoco
// ...so, you can't access the referenced properties through virtual navigation properties:
MyOtherPoco otherPoco1 = myPoco.Poco2; // returns NULL
}
// leave the context and build a new one
using (var db = new MyContext())
{
// Now, the same Find() and Where() methods return a proxy object
var test20 = db.MyPocos.Find(myPoco.Id); // returns a proxy object
var test21 = db.MyPocos.Where(x => x.Id == myPoco.Id).First(); // returns a proxy object
// ...which means the virtual properties can be accessed as expected:
MyOtherPoco otherPoco = myPoco.Poco2; // works as expected
// Note that db.Entry().Entity still returns a POCO:
var test22 = db.Entry(myPoco).Entity; // returns a MyPoco
}
可能有一些魔法咒语可以让添加对象的上下文给你一个代理对象,但我还没有遇到过。