我在 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;
}
最佳答案
问题是传递给 post 方法的实体不是代理,大概是因为它是使用普通的“new”运算符在 Entity Framewortk 之外创建的。
这里有几个选项。首先,您可以修改 MVC Controller 以使用 DbSet.Create
方法创建代理实例。我听说可以用这种方式修改 MVC Controller ,但我自己从未尝试过。例如,而不是做:
var doc = new Document();
在 Controller 中,你会做:
var doc = context.Documents.Create();
如果实体具有适当的虚拟属性(在您的情况下看起来确实如此),则 create 方法允许 EF 创建用于延迟加载的代理。
第二个可能更简单的选择是不使用延迟加载,而是使用显式加载 API。例如,要加载 FileType:
var fileType = context.Entry(doc).Reference(d => d.FileType).Load();
不太可能延迟加载,这需要对上下文的显式引用,但在您的情况下应该没问题。
关于asp.net-mvc - EF4.3 代码优先、MVC、在 POST 操作中附加后延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9695006/