A
A
Anonymous Anonymous2020-11-14 19:23:57
ASP.NET
Anonymous Anonymous, 2020-11-14 19:23:57

How to display the username instead of Id from the database using LINQ?

There are two tables in the database Wallet, Transaction and AspNetUser , you need to make a history of transfers, you just need to display their names instead of the sender and recipient IDs. I did the output of information, but I can’t figure out how to link the ID from the Transaction with AspNetUser through the ID from the Wallet. I know the principle by which I can do this from SQL, but I don’t know how to do this in LINQ yet. Help who knows how this can be arranged.
WalletController.cs

[HttpGet]
        [Route("transactions")]
        public List<Transaction> GetTransactions()
        {
            var TransactionList = new List<Transaction>();
            var userId = _userManager.GetUserId(User);
            var listId = _context.Users.Include(x => x.Wallets).FirstOrDefault(x => x.Id == userId)?.Wallets.Select(x => x.Id).ToList();
            TransactionList = _context.Transactions.Where(x => listId.Contains(x.SourceWalletId) || listId.Contains(x.DestinationWalletId)).ToList();
            TransactionList = TransactionList.Distinct().ToList();
            return TransactionList;
        }


Transaction.cs
using System;

namespace BlazorPaymentSystem.Server.Models
{
    public class Transaction
    {
        public Guid Id { get; set; }
        public Guid SourceWalletId { get; set; }
        public Guid DestinationWalletId { get; set; }
        public decimal Amount { get; set; }
        public DateTime Date { get; set; }
    }
}

ApplicationDbContext.cs
namespace BlazorPaymentSystem.Server.Data
{
    public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
    {
        public ApplicationDbContext(
            DbContextOptions options,
            IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
        {
        }

        public DbSet<Wallet> Wallets { get; set; }
        public DbSet<Transaction> Transactions { get; set; }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
basrach, 2020-11-14
@basrach

I didn't check, but it should be something like this:

var transactionList =
    from transaction in _context.Transactions
    from destinationUser in _context.Users
    from destinationUserWallet in destinationUser.Wallets where destinationUserWallet.Id == transaction.DestinationWalletId
    from sourceUser in _context.Users
    from sourceUserWallet in sourceUser.Wallets where sourceUserWallet.Id == transaction.SourceWalletId		
    where destinationUser.Id == User || sourceUser.Id == User
    select new 
    { 
      sourceUserName = sourceUser.Name, 
      destinationUserName	= destinationUser.Name, 
      transaction
    };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question