You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Fluent API基于非主键建立StripeAccount与StripePayout关联

EF Core 关联配置:通过Fluent API绑定非主键字段

原始实体类

现有两个实体类StripeAccount和StripePayout:

public class StripeAccount
{
   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 StripePayout
{
   public int Id { get; set; }
   public string Status { get; set; }
   public decimal Amount { get; set; }
   public DateTime ArrivalDate { get; set; }
   public string DestinationId { get; set; }
   public int UserId { get; set; }
   public User User { get; set; }
   // 其他属性...
}

需求与问题

创建StripePayout实体时,其DestinationId需与StripeAccount的ExternalAccountId保持一致;查询用户的StripePayouts时,需要关联获取StripeAccount的部分字段(示例查询如下):

var payouts = await _dbContext.StripePayouts.Where(p => p.UserId == id)
    .Select(p => new {
        Amount = p.Amount,
        ArrivalDate = p.ArrivalDate,
        BankName = p.StripeAccount.BankName,
        AccountNumber = p.StripeAccount.AccountNumber
 }).ToListAsync()

问题:如何使用Fluent API建立DestinationId与ExternalAccountId之间的关联?实体类需做哪些修改?

已验证的解决方案

以下是成功实现的步骤:

1. 修改实体类

  • 在StripeAccount中添加集合导航属性,关联对应的StripePayout集合:
public ICollection<StripePayout> StripePayouts { get; set; }
  • 在StripePayout中添加引用导航属性,指向关联的StripeAccount(可按需添加其他属性,如示例中的BalanceTransactionId):
public string BalanceTransactionId { get; set; }
public StripeAccount StripeAccount { get; set; }

2. Fluent API 配置

在DbContext的OnModelCreating方法中,配置两者的关联关系,指定外键为DestinationId,关联的主健为StripeAccount的ExternalAccountId:

modelBuilder.Entity<StripePayout>()
   .HasOne(a => a.StripeAccount)
   .WithMany(b => b.StripePayouts)
   .HasForeignKey(a => a.DestinationId)
   .HasPrincipalKey(b => b.ExternalAccountId);

内容的提问来源于stack exchange,提问作者chuckd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:22:38