[英]Entity Framework Code First Foreign Key adding Index as well
I have simple table definition in EF 6 code-first with simple foreign key. 我在EF 6代码中有简单的表定义 - 首先是简单的外键。
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. 以及如何默认禁用此类索引创建。
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
在程序包管理器控制台中,键入Enable-Migrations
Add-Migration InitialMigration
在程序包管理器控制台中,键入Add-Migration InitialMigration
Up
method with a few statements. 新迁移将添加到Migrations文件夹中,您将在其中看到包含一些语句的Up
方法。 Find the line that adds the foreign key and remove it. 找到添加外键的行并将其删除。 Update-Database
to apply migrations. 在程序包管理器控制台中,键入Update-Database
以应用迁移。 This is assuming you do not have a database yet and are starting from scratch. 这假设您还没有数据库并且从头开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.