我在将查询中的 ApplicationUser
对象拉到 DbContext
时遇到问题。
这是我的 Foo
模型
public class Foo
{
public int Id { get; set; }
public string Title { get; set; }
public ApplicationUser Creator { get; set; }
}
在编辑操作中的 Foo Controller 内部,我想检查请求编辑的用户是否是创建者。
//ApplicationDbContext inherits IdentityDbContext
private ApplicationDbContext appDb { get; set; }
...
public async Task<ActionResult> Edit(int? id)
{
Foo target = appDb.Foos.First(o => o.Id == id);
if (target == null)
{
return HttpNotFound();
}
if (target.Creator.Id != User.Identity.GetUserId())
{
ViewBag.Error = "Permission denied.";
return Redirect(Request.UrlReferrer.ToString());
}
return View(target);
}
问题是由于某些原因 target.Creator
返回 null,尽管所有 Foo
都引用了一个 Creator
对象。在同一个 Controller 中,在细节 Action 中它被拉得很好:
var entry = appDb.Foos.Where(f=>f.Id == id)
.Select(foo => new FooViewModel()
{
Id = foo.Id,
Title = foo.Title,
CreatorId = foo.Creator.Id,
CreatorName = foo.Creator.FirstName,
}).FirstOrDefaultAsync();
我错过了什么?尝试在 Display 查询中访问 foo.Creator
与尝试直接在 Foo 对象上访问它有什么不同?当我请求 Foo 本身时,我认为 EF 会查询 foo.Creator
。
我是否应该将 foo.Creator
改为存储 foo.CreatorId
?
谢谢。
最佳答案
默认情况下不加载导航属性。如果您需要它们,请使用 .Include()
急切加载它们:
Foo target = appDb.Foos.First(o => o.Id == id).Include(f => f.Creator);
您的代码根本不起作用:如果您尝试使用 .First()
查找第一个元素,但它不存在,您将得到一个异常。即,您的代码永远不会命中 if (target == null)
。
您应该使用 .FirstOrDefault()
,或者更好的方法是 Find()
。
关于asp.net-mvc - EF 恢复的对象中的空属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33870899/