db.Ent 。RY()實體總是會把你返回一個POCO,並不會返回處理虛擬導航性能的實現代理對象:
var o = db.Entry(myPoco).Entity; // always returns a POCO
您通常會得到一個代理對象,而不是POCO調用Find()
時或針對數據庫上下文的Where()
。 但是,在對象首次添加到數據庫的上下文中,這些方法將(意外地?)返回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
}
可能有一些神奇的咒語,使在其中添加對象的上下文給你回一個代理對象,但我避風港沒有遇到它。
[將POCO對象轉換爲EntityFramework中的代理對象](http://stackoverflow.com/questions/8174200/convert-poco-object-to-proxy-object-in-entityframework) – Dennis