2017-08-14 72 views
0

我使用一個約定(IStoreModelConvention),我需要知道如果AssociationType.IsForeignKey是真實的。目標是重新映射映射表中的所有外鍵。例如,刪除下劃線並組成從類和屬性名稱派生的全新名稱。實體框架Core 2中的AssociationType等效於什麼?

現在的問題是:在Entity Framework Core 2中是否存在與AssociationType.IsForeignKey的等價物,或者如何完成這種類型的自定義?

回答

1

EF Core 2爲ForeignKeys提供了不同的(或更好的)命名系統。該名稱構建爲FK_Table_ReferencedTable_FKProperties,其中表是定義FK約束的地方。 ReferencedTable是主要的一面。而FKProperties是_分隔的外鍵屬性列表。也許它會匹配你想要的命名系統。

雖然如果您仍然想自定義外鍵屬性的名稱,那麼在ef內核中還沒有用戶定義的約定支持。但EF Core允許您遍歷模型元數據以按照您的需要進行配置。在派生的DbContextOnModelCreating方法中,您可以根據需要輸入以下代碼來命名FK。

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    // Configure model 
    foreach (var entityType in modelBuilder.Model.GetEntityTypes()) 
    { 
     foreach (var declaredForeignKey in entityType.GetDeclaredForeignKeys()) 
     { 
      declaredForeignKey.Relational().Name = "<Construct_FK_Name>"; 
     } 
    } 
} 
+0

謝謝你,這聽起來很不錯。我會測試。 – gabomgp