我在 MVC 3 应用程序中使用带有 Code-First 的 Entity Framework 4.3。我有一个 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”运算符在实体框架之外创建的。
这里有几个选项。首先,您可以修改 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();
不太可能延迟加载,这需要对上下文的显式引用,但在您的情况下应该没问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)