我创建了三个不同的类和一个存储不同类型地址的基类。基类是与用户相关的邮政地址(当前地址附加到谁)和邮政,其中包含有关邮政编码和城市的信息。
public class PostalAddress
{
public virtual User User { get; set; }
public DateTime LastUsed { get; private set; }
public string OrientationNumber { get; set; }
public int UserId { get; set; }
public int PostId { get; set; }
public int Id { get; set; }
public virtual Post Post { get; private set; }
public string Street { get; set; }
}
public class Post
{
public Post()
{
InvoicingAddresses = new List<InvoicingAddress>();
ShippingAddresses = new List<ShippingAddress>();
UserAddresses = new List<UserAddress>();
}
public virtual City City { get; set; }
public virtual ICollection<InvoicingAddress> InvoicingAddresses { get; private set; }
public virtual ICollection<ShippingAddress> ShippingAddresses { get; private set; }
public virtual ICollection<UserAddress> UserAddresses { get; private set; }
public int CityId { get; set; }
public int Id { get; set; }
public string ZipCode { get; set; }
}
使用 PostalAddressMap 类映射 PostalAddress 类
public class PostalAddressMap : EntityTypeConfiguration<PostalAddress>
{
public PostalAddressMap()
{
// Primary Key
HasKey(t => t.Id);
// Properties
// Table & Column Mappings
ToTable("PostalAddress");
Property(t => t.Id).HasColumnName("Id");
Property(t => t.LastUsed).HasColumnName("LastUsed").HasColumnType("datetime2");
Property(t => t.OrientationNumber).HasColumnName("OrientationNumber");
Property(t => t.UserId).HasColumnName("UserId");
Property(t => t.PostId).HasColumnName("PostId");
Property(t => t.Street).HasColumnName("Street");
// Relationships
HasRequired(t => t.Post).WithMany(t => t.InvoicingAddresses).HasForeignKey(d => d.PostId);
HasRequired(t => t.User)
.WithMany(t => t.UserAddressess)
.HasForeignKey(d => d.UserId);
}
}
InvoicingAddress、ShippingAddress 和 UserAddress 类使用Table per hierarchy方法从 PostalAddress 类继承。如果我想使用 line 设置关系
HasRequired(t => t.Post).WithMany(t => t.InvoicingAddresses).HasForeignKey(d => d.PostId);
我收到编译器错误无法将类型“System.Collections.Generic.ICollection<InvoicingAddress>”隐式转换为“System.Collections.Generic.ICollection<PostalAddress>”。存在显式转换(您是否缺少演员表?)
请问,你能帮我如何在 PostalAddress 子类和其他 TPT 类型之间设置外键吗?
感谢您提供任何有用的答案。