我有这两类账户和支付。
public class Account
{
public int Id { get; set; }
public string BankName { get; set; }
public string AccountNumber { get; set; }
public string Currency { get; set; }
public string ExternalAccountId { get; set; }
.
.
}
public class Payout
{
public int Id { get; set; }
public string Status { get; set; }
public decimal Amount { get; set; }
public DateTime ArrivalDate { get; set; }
public string BalanceTransactionId { get; set; }
public int UserId { get; set; }
public User User { get; set; }
.
.
}
当我收到并创建一个新的“付款”实体时,“BalanceTransactionId”与帐户中的“ExternalAccountId”相同。
当我获取用户“支出”时,我想查询并从“帐户”中获取一些值
例如
var payouts = await _dbContext.Payouts.where(p => p.UserId == id)
.Select(p => new {
Amount = p.Amount,
ArrivalDate = p.ArrivalDate,
BankName = p.Account.BankName,
AccountNumber = p.Account.AccountNumber
}).ToListAsync()
问题 - 如何使用流畅的 API 在“BalanceTransactionId”和“ExternalAccountId”之间创建这种关系,它在类中会是什么样子?
更新 - 我添加了这个但不确定它是否正确
记账
public ICollection<Payout> Payouts { get; set; }
付款
public string BalanceTransactionId { get; set; }
public Account Account { get; set; }
到数据上下文
modelBuilder.Entity<Account>()
.HasMany(t => t.Payouts)
.WithOne(g => g.Account)
.HasForeignKey(g => g.BalanceTransactionId)
.OnDelete(DeleteBehavior.Restrict);
你可以这样配置它:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Payout>()
.HasOne<Account>()
.WithMany<Payout>()
.HasForeignKey<Payout>(p => p.BalanceTransactionId)
.HasPrincipalKey(b => b.ExternalAccountId);
}
要查询值,您可以使用以下语法:
var payouts = await _dbContext.Payouts.where(p => p.UserId == id)
.Select(p => new {
Amount = p.Amount,
ArrivalDate = p.ArrivalDate,
BankName = _dbcontext.Accounts.Single(a => p.BalanceTransactionId == a.ExternalAccountId).BankName,
AccountNumber = _dbcontext.Accounts.Single(a => p.BalanceTransactionId == a.ExternalAccountId).AccountNumber
}).ToListAsync()