简体   繁体   中英

EF Code first :Remove Extra foreign keys from a central many to many relationships table

I have a central table to handle translations, many entities could have a collection of translations. I'm using EF 6.0 code first. For each entity EF generate a foreign key in Translation table, to avoid this, I decide to add 3 columns :TableName, ColumnName and EntityKey to point to the given table.

public class CurrencyModel
{
  // more staff here 
  public ICollection<TranslationModel> Translations {get; set; }
}
public class CityModel
{
  // more staff here 
  public ICollection<TranslationModel> Translations {get; set; }
}

public class CountryModel
{
  // more staff here 
  public ICollection<TranslationModel> Translations {get; set; }
}

public class CategoryModel
{
  // more staff here 
  public ICollection<TranslationModel> Translations {get; set; }
}

How can I force EF to do not generate a foreign key for each table ? Thank you in advance for your help

在创建和添加迁移之后,以及在更新数据库之前,您应该使用流利的api,转到DbContext类并检查OnModelCreating方法。在此方法中,您可以在某些实体上看到.HasForeignKey(e => e ....)。 。OnModelCreating方法是您可以覆盖EF约定并强制其例如不为每个表生成外键的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM