Entity Framework Code First foreign key with index added

I have a simple table definition in EF 6 code with the first foreign key.

public class Address { /// <summary> /// Gets or sets the id. /// </summary> [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column(Order = 1)] public int Id { get; set; } /// <summary> /// Gets or sets the town. /// </summary> public virtual Town Town { get; set; } /// <summary> /// Gets or sets the paf address town id. /// </summary> [Column(Order = 2)] public int TownId { get; set; } } 

When creating a table, a foreign key is created, as well as an index. I wonder why, since such an index is usually very inefficient, and for large databases it causes a lot of problems. So why did he create this index instead of a foreign key. And how to disable the creation of this index by default.

+5
source share
1 answer

This is just an agreement with the Entity Framework. If you do not like this, you can enable migration in your project and change the migration to not include a foreign key. I do not agree with your statement that it is ineffective.

To enable database migration, follow these steps:

  • In the Package Manager console, enter Enable-Migrations
  • In the package manager console, enter Add-Migration InitialMigration
  • A new migration will be added to the Migrations folder, in which you will see the Up method with several statements. Find the line that adds the foreign key and deletes it.
  • In the Package Manager console, enter Update-Database to apply the migration.
  • Repeat steps 2-4 for any new changes that come in.

It is assumed that you do not yet have a database and start from scratch.

+1
source

Source: https://habr.com/ru/post/985375/


All Articles