基于示例,我创建了以下自定义连接表(使用 EF Core 5),因为我需要在我的自定义连接表中添加一个额外的属性:
modelBuilder.Entity<Property>(property =>
{
property
.HasMany(_ => _.Addresses)
.WithMany(_ => _.Properties)
.UsingEntity<PropertyAddress>(
_ => _.HasOne(_ => _.Address).WithMany().HasForeignKey(_ => _.AddressId),
_ => _.HasOne(_ => _.Property).WithMany().HasForeignKey(_ => _.PropertyId));
});
public class PropertyAddress
{
public string PropertyId { get; set; }
public string AddressId { get; set; }
public int SequenceNumber { get; set; }
public Property Property { get; set; }
public Address Address { get; set; }
}
public class Property
{
public ICollection<Address> Addresses { get; set; }
}
public class Address
{
public ICollection<Property> Properties { get; set; }
}
自定义连接表PropertyAddress
按预期工作,但是:如何(以编程方式)PropertyAddress.SequenceNumber
在保存/更新记录之前设置自定义属性的值?(因为整个加入机制(现在)仍然由 EF Core '在幕后'处理。)