EF4.3 Code-First, MVC, Lazy Loading After Attaching in POST Action

杀马特。学长 韩版系。学妹 提交于 2019-12-06 09:56:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!