如何访问相关数据并将外键转换为对象以显示其属性

时间:2018-06-06 16:12:24

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

我有

class User {
...
...
ICollection<Transaction> transactionsUserMade;
}

class Transaction {
int ID;
int userThatSentMoneyID;
int userToWhomHeSentMoneyID;
}

我试图制作个人资料页面,用户可以看到他所做的所有交易以及向谁发送。我设法将用户和交易联系起来,但我得到了整数值,因为我应该使用

await _context.Users
    .Include(u => u.transactionsUserMade)
    .AsNoTracking()
    .FirstOrDefaultAsync(u => u.ID == userId);

如何将这些ID转换为用户的实际对象,以便我可以获取用户名并在Razor Page上显示它们。

2 个答案:

答案 0 :(得分:0)

找到一个解决方案。我通过添加User userThatRecievedMoney属性来调整Transaction类。在从特定用户获得交易后,我手动设置该属性。

foreach(var transaction in _user.transactionsUserMade)
{
    transaction.userThatRecievedMoney = _context.Users
       .Where(u => u.ID == transaction.userToWhomHeSentMoneyID).FirstOrDefault();
}

答案 1 :(得分:0)

只要您可以修改这些实体模型Navigation PropertyUser,就可以使用Transaction来帮助您。

public class UserEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }

    public List<TransactionEntity> TransactionsAsSender { get; set; }
    public List<TransactionEntity> TransactionsAsRecipient { get; set; }
}

public class TransactionEntity
{
    public int Id { get; set; }
    public double Amount { get; set; }
    public string Note { get; set; }

    // Foreign key to UserEntity
    public int SenderId { get; set; }
    public UserEntity Sender { get; set; }

    // Foreign key to UserEntity
    public int RecipientId { get; set; }
    public UserEntity Recipient { get; set; }
}

然后你需要建立他们的关系。

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<UserEntity>(b => {
            b.HasKey(x => x.Id);
            b.Property(x => x.Name).IsRequired();
            b.Property(x => x.Email).IsRequired();

            b.ToTable("User");
        });

        builder.Entity<TransactionEntity>(b => {
           b.HasKey(x => x.Id);
           b.Property(x => x.Amount).IsRequired();

           // Configure relationships
           b.HasOne(x => x.Sender)
               .WithMany(u => u.TransactionsAsSender)
               .HasForeignKey(x => x.SenderId);

           b.HasOne(x => x.Recipient)
               .WithMany(u => u.TransactionsAsRecipient)
               .HasForeignKey(x => x.RecipientId);

           b.ToTable("Transaction");
        });
    }

    public DbSet<UserEntity> Users { get; set; }
    public DbSet<TransactionEntity> Transactions { get; set; }
}

设置关系后,您可以通过导航属性轻松查询相关数据。

例如,假设您有一个名为UserProfileViewModelUserProfileTransactionViewModel的视图模型,以包含显示所需的信息。

public class UserProfileViewModel
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string UserEmail { get; set; }

    public IEnumerable<UserProfileTransactionViewModel> TransactionsAsSender { get; set; }
    public IEnumerable<UserProfileTransactionViewModel> TransactionsAsRecipient { get; set }
}

public class UserProfileTransactionViewModel
{
    public int TransactionId { get; set; }
    public string Sender { get; set; }
    public string Recipient { get; set; }
    public string Amount { get; set; }
}

在控制器中,

var user = _dbContext.Users
    .AsNoTracking()
    .Include(x => x.TransactionsAsSender)
    .Include(x => x.TransactionsAsRecipient)
    .SingleOrDefault(x => x.Id == userId);

if (user == null)
{
    return NotFound();
}

var vm = new UserProfileViewModel
{
    UserId = user.Id,
    UserName = user.Name,
    UserEmail = user.Email,
    TransactionsAsSender = user.TransactionsAsSender
        .Select(x => new UserProfileTransactionViewModel
        {
            TransactionId = x.Id,
            Sender = x.Sender.Name,
            Recipient = x.Recipient.Name,
            Amount = x.Amount.ToString("c")
        }),
    TransactionsAsRecipient = user.TransactionsAsRecipient
         .Select(x => new UserProfileTransactionViewModel
        {
            TransactionId = x.Id,
            Sender = x.Sender.Name,
            Recipient = x.Recipient.Name,
            Amount = x.Amount.ToString("c")
        })      
};

return View(vm);

您甚至可以只列出UserProfileViewModel之外的所有交易。您可以合并TransactionsAsSender中的TransactionsAsRecipientUserEntity来填充列表。

放弃:

我用手和想象力写下了所有东西:p