EF CORE - 创建一对多地图
Posted
技术标签:
【中文标题】EF CORE - 创建一对多地图【英文标题】:EF CORE - Create one-to-many map 【发布时间】:2020-12-16 20:32:00 【问题描述】:我正在尝试创建一个一对多的地图,我尝试了很多方法来做到这一点,但我还没有弄清楚:/
我有 2 个实体,Wallet 和 Transfer,我想在 Transfer 中添加一个 FK WalletId,所以一次转账只有一个钱包,但一个钱包可以关联多个转账。
Wallet.cs -
public class Wallet
public int Id get; private set;
public decimal Balance get; private set;
Transfer.cs -
public class Transfer
#region Properties
public int Id get; private set;
public decimal Value get; private set;
public DateTime? TransferDate get; private set;
public DateTime RegisterDate get; private set;
public ETransferType TransferType get; private set;
WalletMap.cs -
public class WalletMap : IEntityTypeConfiguration<Wallet>
public void Configure(EntityTypeBuilder<Wallet> builder)
builder.HasKey(x => x.Id);
builder.Property(x => x.Balance).HasColumnType("Money").IsRequired();
TransferMap.cs -
public class TransferMap : IEntityTypeConfiguration<Transfer>
public void Configure(EntityTypeBuilder<Transfer> builder)
builder.HasKey(x => x.Id);
builder.Property(x => x.Value).HasColumnType("Money").IsRequired();
builder.Property(x => x.TransferDate);
builder.Property(x => x.RegisterDate).IsRequired();
builder.Property(x => x.TransferType).IsRequired();
【问题讨论】:
【参考方案1】:添加foreign key
和navigation property
:
public class Wallet
public int Id get; set;
public decimal Balance get; set;
public virtual ICollection<Transfer> Transfers get; set; // Navigation Property
public class Transfer
pubic int Id get; private set;
public decimal Value get; private set;
public Datetime? TransferDate get; private set;
//.....Remaining properties
public int WalletId get; set; //Foreign Key
public virtual Wallet Wallet get; set; //Reference Navigation
这将添加所需的foreign key
和navigation properties
。
//using fluent api
protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<Transfer>().HasOne(x => x.Wallet)
.WithMany(x => x.Transfers)
.HasForeignKey(x => x.WalletId);
modelBuilder.Entity<Wallet>.HasMany(x => x.Transfers)
.WithOne();
【讨论】:
【参考方案2】:到 Wallet.cs 添加:
public virtual ICollection<Transfer> Tranfers get; set;
到 Transfer.cs 添加:
public virtual Wallet Wallet get; set;
在您的配置块中添加 TransferMap.cs:
builder.HasRequired(x => x.Wallet).WithMany(x => x.Transfers).Map(x => x.MapKey("WalletId")).WillCascadeOnDelete();
如果您没有在数据库中配置级联删除,您可以删除 WillCascadeOnDelete()。这假设您已经在数据库的 Transfers 表中定义了 WalletId。
【讨论】:
以上是关于EF CORE - 创建一对多地图的主要内容,如果未能解决你的问题,请参考以下文章