我有問題將Fluent API擴展到我的繼承類。我採用了TPT(table per type)方法,並且每種類型的繼承都有一個表。我喜歡每種類型的表格,因爲數據庫完全標準化並易於維護。我收到一個錯誤信息,說明article指示我做的onModelCreating
方法。它正在失去用戶和角色實體的密鑰。實體框架代碼首先覆蓋TPM繼承onModelCreating()繼承擰緊身份用戶和角色模型
抽象基類
namespace Home_Warranty.Models
{
public abstract class Vendor
{
[Key]
public int VendorID { get; set; }
[Required]
public string CompanyName { get; set; }
[Required]
public int StreetNumber { get; set; }
[Required]
public string StreetName { get; set; }
}
}
繼承ServiceCompany類從供應商
namespace Home_Warranty.Models
{
[Table("ServiceCompanies")]
public class ServiceCompany : Vendor
{
public string ACHClaim { get; set; }
public virtual ICollection<SubContractorCompany> SubContractorCompanies{ get; set; }
public virtual ICollection<ServiceCompanyUser> SubContractorUsers { get;set; }
}
}
當我加入了實體模型,以便能夠與onModelCreating()
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Vendor> Vendors { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ServiceCompany>().ToTable("ServiceCompanies");
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
,我發現了流利的API更新數據庫時在遷移時出現以下錯誤。這絕對是因爲我過度使用onCreateModel函數。
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
One or more validation errors were detected during model generation:
Home_Warranty.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
Home_Warranty.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
- 這似乎並不像處理這一問題的最佳途徑。我可以在其他地方添加此代碼,並獲得我想要的實際結果而無需搞亂用戶和角色模型?
- 我希望能夠通過流暢的API來做到這一點。
var ListofServiceCompanies = db.ServiceCompanies.All()
,或者我應該只是經過供應商實體呢?
var ListofServiceCompanies = db.Vendor.SelectMany(Vendor is a ServiceComapny...etc)
我更喜歡正確設置實體,使代碼更好,更易於使用。任何見解或知識,表示讚賞。
如果基本的DbContext類型有流利的映射,你不運行它。您對OnModelCreating的重寫不會鏈接到base.OnModelCreating。 –
你可以用代碼創建一個例子,鏈接到base.OnModelCreating? – dev8989