asp.net-mvc - EF 恢复的对象中的空属性

标签 asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6

我在将查询中的 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/

相关文章:

asp.net-mvc - 模型在局部 View 中为空

asp.net-mvc - SSL 握手问题? (是 : Web page hangs, 只有清除浏览器缓存有帮助)

asp.net-mvc - ASP.Net MVC 5 + SignalR + Ninject

entity-framework - EF Core 3 的 DbContextScope 模式

c# - Entity Framework 代码优先 - 将 smallint 和整数转换为 int32

c# - 如何在 EF Core 中自动映射 TPH 派生类?

asp.net-mvc-5 - ASP.NET MVC 5 自定义 RazorViewEngine 用于多个门户结构

Asp.Net MVC 5 绑定(bind)参数完全来自正文

c# - MVC id 值始终为 null

c# - 改文件名显示不改原名