我想从外键中的外键中获取项目(如果有任何意义......)

I want to get item from a foreign key inside a foreign key (if that makes any sense...)

我正在使用 ASP.NET 核心身份。用户 ID 将在邀请模型中显示为 FK,我正在尝试显示邀请中的所有用户以及所需信息。

我想在分配给用户的 GameID 中显示 GameName

所以它会像 invite show GameName (FK in user) GameTag (user) 而不是带有数字的 GameID

型号类:

public class Invite
{
    public int ID { get; set; }
    [ForeignKey("UserId")]    // ICollection<Invite> in User 
    [Display(Name = "Users")]
    public virtual ApplicationUser User { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public string Description { get; set; }
    [ForeignKey("GameID")] 
    public int? GameID { get; set; }
    public string GameTag { get; set; }
    public virtual ICollection<Invite> Invite { get; set; }
}

public class Game
{
    public int ID { get; set; }

    [Display(Name = "Game")]
    public string GameName { get; set; }
    public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }//Allow Users to get Games FKID (Foreign key ID)
}

获取邀请控制器索引中的邀请列表并将它们放入邀请剃刀索引页面的视图包中。它只显示 GameID,它是用户内部的 FK,我不知道如何从分配给用户 FK

的 Invite 中获取游戏 FK 中的信息
// GET: Invites
public async Task<IActionResult> Index()
{
    ViewBag.InviteList = new List<String>();
    var invite = _context.Invites;
    var theuser = _context.ApplicationUser;

    foreach (Invite i in invite)
    {
         foreach (ApplicationUser tu in theuser)
         {
             if (i.User.Id == tu.Id)
             {
                 ViewBag.InviteList.Add(tu.GameID + " " +tu.GameTag);
             }
         }
    }

    return View(await _context.Invites.ToListAsync());
}

如果有人明白我想说的意思,欢迎提出更好的标题

您的代码未正确实现(除了显示 GameName 的主要要求外)。实际上 Game 中的信息并不是直接从 ApplicationUser 中引用的。不确定为什么不将其包含在 class 中(连同 GameID)。假设你这样做(包括 属性 Game),代码可以像这样简单:

var invites = await _context.Invites.AsNoTracking()
                            .Include(e => e.User.Game).ToListAsync();

//NOTE: this can contain duplicate strings added to `InviteList`, unless you 
//include more data field in each item.
foreach (Invite i in invites)
{
     ViewBag.InviteList.Add(i.User.Game.GameName + " " + i.User.GameTag);         
}

如果你不想在ApplicationUser中包含属性 Game,你需要加入实体,像这样:

var games = await (from invite in _context.Invites
                   join game in _context.Games on invite.User.GameID equals game.ID
                   select new { game.GameName, invite.User.GameTag }).AsNoTracking().ToListAsync();
//to avoid duplicate items (as noted in the previous code)
ViewBag.InviteList = games.GroupBy(e => e.GameName)
                          .Select(g => g.First())
                          .Select(e => $"{e.GameName} {e.GameTag}").ToList();