[英]Multiple Inheritance Levels Using Entity Framework TPT
考慮以下表模式:
我想使用實體框架按類型的表(Fluent API)映射到以下類圖:
我怎樣才能做到這一點? 我曾嘗試像Microsoft網站上的示例一樣進行操作,但似乎沒有示例涵蓋兩層繼承方案,並且出現了與無效區分符列相關的錯誤,依此類推。 我為每種類型使用一個EntityTypeConfiguration
。 如何指定級聯孩子的外鍵名稱?
如果有人有如何進行這種映射的例子,我將永遠感激。
謝謝!
因此,每種類型的表對您的架構不太有效,因為每種類型的表通過共享主鍵將表鏈接在一起。 您可以修改架構,以便將UserAccounts,ExternalUserAccounts和SystemUserAccounts都鍵入到UserAccountId上。 然后,下面的代碼接近您想要的代碼。 否則,您將需要使用常規關聯屬性。
public class UserAccount
{
public int UserAccountId {get;set;}
public int UserId {get;set;}
public DateTime LastLogin {get;set;}
public bool IsLocked {get;set;}
public bool IsActive {get;set;}
public User User {get;set;}
}
public class ExternalUserAccount : UserAccount
{
public int ExternalAccountId {get;set;}
public string ProviderName {get;set;}
public string ProviderUserName {get;set;}
}
public class SystemUserAccount : UserAccount
{
public int SystemUserAccountId {get;set;}
public string PasswordHash {get;set;}
public string Token {get;set;}
}
public class User
{
public int UserId {get;set;}
public string Name {get;set;}
public string Description {get;set;}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserAccount>().ToTable("UserAccounts");
modelBuilder.Entity<UserAccount>().HasKey(ua => ua.UserAccountId);
modelBuilder.Entity<UserAccount>().HasRequired(ua => ua.User)
.WithMany()
.HasForeignKey(ua => ua.UserId);
modelBuilder.Entity<ExternalUserAccount>().ToTable("ExternalUserAccounts");
modelBuilder.Entity<SystemUserAccount>().ToTable("SystemUserAccounts");
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<User>().HasKey(u => u.UserId);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.