【问题标题】:EF4.3 Code-First, MVC, Lazy Loading After Attaching in POST ActionEF4.3 代码优先、MVC、在 POST 操作中附加后延迟加载
【发布时间】:2012-03-14 11:38:49
【问题描述】:

我在 MVC 3 应用程序中使用 Entity Framework 4.3 和 Code-First。我有一个 POST 操作,它获取一个实体作为其参数,然后将该实体标记为已修改以更新数据库。它是一个文档实体,具有对文件类型的引用。

 [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);
 }

将实体附加到上下文后,我是否应该能够延迟加载该实体的属性?

有趣的是,当我在控制台应用程序中尝试此操作时,它似乎可以工作。

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;
}

【问题讨论】:

    标签: asp.net-mvc entity-framework lazy-loading model-binding


    【解决方案1】:

    问题在于传递给 post 方法的实体不是代理,可能是因为它是在实体框架之外使用普通的“new”运算符创建的。

    这里有几个选项。首先,您可以修改 MVC 控制器以使用 DbSet.Create 方法创建代理实例。我听说可以通过这种方式修改 MVC 控制器,但我自己从未尝试过。例如,不要这样做:

    var doc = new Document();
    

    在控制器中,你会这样做:

    var doc = context.Documents.Create();
    

    如果实体具有适当的虚拟属性,则 create 方法允许 EF 创建延迟加载代理,在您的情况下,它看起来确实如此。

    第二个可能更简单的选择是不使用延迟加载,而是使用显式加载 API。例如,要加载 FileType:

    var fileType = context.Entry(doc).Reference(d => d.FileType).Load();
    

    不太可能延迟加载,这需要对上下文的显式引用,但在您的情况下应该没问题。

    【讨论】:

    • 谢谢!使用您的解释,我能够找到一个简单的解决方案来实现生成代理的模型绑定器。这是对我有帮助的文章的链接。 bit.ly/ydCjOm
    猜你喜欢
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2012-03-24
    • 2011-05-03
    • 1970-01-01
    相关资源
    最近更新 更多