问题
I'm using Entity Framework 4.3 with Code-First in an MVC 3 application. I have a POST action that gets an entity as its' parameter, and then marks the entity as modified to update the database. It's a Document entity that has a reference to a File Type.
[HttpPost]
public ActionResult Example(Document model)
{
// fileType is null, as expected
var fileType = model.FileType;
// attach and mark the entity as modified, save changes
Context.Entry(model).State = EntityState.Modified;
Context.SaveChanges();
// fileType is still null?
fileType = model.FileType;
return View(model);
}
After attaching an entity to the context, shouldn't I be able to lazy-load properties on that entity?
Interestingly, when I try this in a console application it seems to work.
static void Main()
{
// create a new context
var context = new Context();
// get the first document and detach it
var doc = context.Documents.First();
context.Entry(doc).State = EntityState.Detached;
// fileType is null, as expected
var fileType = doc.FileType;
// dispose and create a new context
context.Dispose();
context = new Context();
// attach the entity and mark it as modified
context.Entry(doc).State = EntityState.Modified;
// fileType is not null, which is the desired outcome
fileType = doc.FileType;
}
回答1:
The problem is that the entity passed to the post method is not a proxy, presumably because it was created outside of the Entity Framewortk using the normal "new" operator.
There are a few options here. First, you could modify the MVC controller to create proxy instances by using the DbSet.Create
method. I've heard it is possible to modify the MVC controller in this way, but never tried it myself. For example, instead of doing:
var doc = new Document();
in the controller, you would do:
var doc = context.Documents.Create();
The create method lets EF create a proxy for lazy loading, if the entity has appropriate virtual properties, which in your case it looks like it does.
A second and potentially easier option is to not use lazy loading but instead use the explicit loading APIs. For example, to load FileType:
var fileType = context.Entry(doc).Reference(d => d.FileType).Load();
Unlikely lazy loading, this needs an explicit reference to the context, but in your case that should be okay.
来源:https://stackoverflow.com/questions/9695006/ef4-3-code-first-mvc-lazy-loading-after-attaching-in-post-action