我創建了三個不同的類和一個存儲不同類型地址的基類。 基類是郵遞地址,它與用戶(當前地址附加到)和郵政有關,其中包含有關郵政編碼和城市的信息。在EF中定義外鍵4.3.1首先使用TPH的代碼
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; }
}
類的PostalAddress使用類PostalAddressMap
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類繼承映射。如果我想用線
HasRequired(t => t.Post).WithMany(t => t.InvoicingAddresses).HasForeignKey(d => d.PostId);
設置的關係,我收到編譯器錯誤無法隱式轉換類型「了System.Collections.Generic.ICollection <InvoicingAddress>」到「了System.Collections.Generic.ICollection <的PostalAddress >」。存在明確的轉換(你是否缺少演員?)
請你能幫我一下,我如何在PostalAddress子類和其他TPT類型之間設置外鍵?
謝謝你的任何有用的答案。
謝謝Slauma這麼多,我改變了我的代碼由您的建議,它沒有任何問題的工作。 –