【问题标题】:Entity Framework Relation with ApplicationUser实体框架与 ApplicationUser 的关系
【发布时间】:2021-04-12 15:50:19
【问题描述】:

您好,我无法与 ApplicationUser 类建立关系,您无法浏览!有人可以帮忙吗?

public class ApplicationUser : IdentityUser
{
    public ICollection<Book> Book{ get; set; }
}

public class Book
{

    public string UserID { get; set; }
    [ForeignKey("UserID")]
    public ApplicationUser ApplicationUser { get; set; }
}

在Controller中获取模型

// 获取:书籍 公共异步任务索引() {

    var list = from s in _context.Books select s;

    ApplicationUser ApplicationUser = await _userManager.GetUserAsync(HttpContext.User);

        if (!await _userManager.IsInRoleAsync(ApplicationUser , "Admin"))
        {
            list = list.Where(s => s.ApplicationUser == ApplicationUser);
        }

        list = list.Where(s => s.State== BookUtils.States.ACTIVE);

    return View(await list.AsNoTracking().ToListAsync());
}

当我尝试浏览模型 Book.cshtml @item.ApplicationUser = NULL ????

有人可以帮忙导航吗?

【问题讨论】:

  • 您还没有向我们展示您是如何在控制器操作方法中获取模型的?
  • 我添加了信息
  • 好的,您没有在查询中获取用户。此外,您在这里拥有的 linq 是多余的。你可以直接return View(await _context.Books.Include(b =&gt; b.ApplicationUser).ToListAsync());
  • 我这样做是因为我必须应用过滤器,我已经在上面更新了。有没有更有效的方法来做到这一点?我必须做包含吗?不应该是自动的吗?
  • 因为我的 Book 与另一个类有关系,所以我想做 Book.ApplicationUser.OtherClass.name 而不是我想担心包含依赖关系!

标签: asp.net asp.net-mvc asp.net-core


【解决方案1】:

试试这个:

      ApplicationUser ApplicationUser = await _userManager.GetUserAsync(HttpContext.User);

        if (!await _userManager.IsInRoleAsync(ApplicationUser , "Admin"))
        {
                  var list = await _context.Books 
                        .Where( b=>  b.UserId==ApplicationUser.UserId
                              && b.State== BookUtils.States.ACTIVE )
                       .AsNoTracking()
                       .ToListAsync();
              return View(list);
       }  
return ...else

【讨论】:

  • 您好,谢谢。在上面的模型中,有一些方法可以浏览模型而不在查询选择中包含依赖项?例如我打算 Book.ApplicationUser.OtherClass.OtherRelatedClass.name
  • 视情况而定。您能否发布完整的 ApplicationUser 以及您已经尝试过的内容?
  • Book book = await _context.Book .FindAsync(id); book .ApplicationUser.Email 。在这个例子中,我不想担心在选择中包含 ApplicationUser。我希望实体框架是关于依赖关系的。但如果它不包含它,它会给出 Book.ApplicationUser = NULL。它不应该能够使用主键/外键浏览属性吗?
  • 在这种情况下,如果您想在书籍实例中获得更多信息,则必须包含一些内容。但是如果你使用 await _context.Book .Select({}).FirstOrDefaultAsync(...);你可能不需要。我需要查看结果对象。
猜你喜欢
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 2017-10-01
相关资源
最近更新 更多