I have simple table definition in EF 6 code-first with simple 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 the table is created it is creating a foreign key as well as an index. I wonder why, because such index is usually very inefficient, and for big databases it causing a lot of issues. So why it created that index instead of foreign key only. And how to disable by default such index creating.
To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship. I mean to say, define the foreign key table. Thanks for reading this article, hope you enjoyed it.
Entity Framework Creating indexes in Entity Framework Code First. As of EntityFramework version 6.1, it is possible to create index in the database, specifying this directly in the classes in the source code. This creation of the indexes is carried out through the Index attribute directly to the class property.
The Code First primary key convention is: Property with name " Id " or {class name} + " Id " will act as the primary key for that entity. If you will run the application, it will create _MigrationHistory and Students tables where " StudentId " is the primary key of the Students table.
When you change the relationship of the objects attached to the context by using one of the methods described above, Entity Framework needs to keep foreign keys, references, and collections in sync.
This is just a convention of Entity Framework. If you don't like it, then you can enable migrations on your project and change the migration to not include the foreign key. I disagree with your assertion that it is inefficient, though.
To enable database migrations do the following:
Enable-Migrations
Add-Migration InitialMigration
Up
method with a few statements. Find the line that adds the foreign key and remove it.Update-Database
to apply migrations.This is assuming you do not have a database yet and are starting from scratch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With