如何访问 EF Core 中联结表的子表?

问题描述 投票:0回答:1

我这里有一个方法,可以从

Rewards
表中检索
UserId
的所有
UserReward

public async Task<IList<Reward>> GetAllRewardsByUserIdAsync(Guid userId)
{
    var userRewards = await context.UserReward
        .Include(d => d.User)
        .Include(d => d.Reward)
        .AsNoTracking()
        .Where(d => d.ApplicationUserId == userId)
        .ToListAsync();

    IList<Reward> rewards = new List<Reward>();

    foreach (Reward reward in userRewards)
    {
        rewards.Add(reward);
    }

    return rewards;
}

当然我得到了错误

Can't convert UserReward into Reward
但是我应该怎么做呢?

这里是

ApplicationUser
表、
Reward
表和
UserReward
表:

public class ApplicationUser : IdentityUser<Guid>
{
    public ApplicationUser()
    {
    
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Guid CategoryId { get; set; }
    public Category Category { get; set; }
    public IList<Reward> Rewards { get; set; }
    public DateTime CreatedDateTime { get; set; }
}

public class Reward
{
    public Guid RewardId { get; set; }
    public string Name { get; set; }
    public bool HasBeenUsed { get; set; }
    public IList<ApplicationUser> Users { get; set; }
    public DateTime ExpiresOn { get; set; }
}

public class UserReward
{
    public Guid ApplicationUserId { get; set; }
    public ApplicationUser User { get; set; }

    public Guid RewardId { get; set; }
    public Reward Reward { get; set; }
}
c# asp.net-core entity-framework-core
1个回答
0
投票

您可以从

ApplicationUser

开始查询
public async Task<IList<Reward>> GetAllRewardsByUserIdAsync(Guid userId)
{
    var rewards = await context.ApplicationUser
        .AsNoTracking()
        .Where(u => u.ApplicationUserId == userId)
        .SelectMany(u => u.Rewards)
        .ToListAsync();

    return rewards;
}
© www.soinside.com 2019 - 2024. All rights reserved.