实体框架代码第一个外键添加指数 [英] Entity Framework Code First Foreign Key adding Index as well
问题描述
public class Address
{
///< summary>
///获取或设置ID。
///< / summary>
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order = 1)]
public int Id {get;组; }
///< summary>
///获取或设置城镇。
///< / summary>
public virtual Town Town {get;组; }
///< summary>
///获取或设置paf地址城镇ID。
///< / summary>
[Column(Order = 2)]
public int TownId {get;组; }
}
当表创建时,它正在创建一个外键以及一个指数。我不知道为什么,因为这样的索引通常是非常低效的,而对于大的数据库,它引起很多问题。那么为什么它只创建该索引而不是外键。而如何在默认情况下禁用这样的索引创建。
这只是一个Entity Framework的约定。如果您不喜欢,那么您可以启用项目的迁移,并将迁移更改为不包括外键。我不同意你的说法,这是低效的。
要启用数据库迁移,请执行以下操作:
- 在包管理器控制台中,键入
启用迁移
- 在包管理器控制台中,键入
添加迁移初始迁移
- 将迁移迁移添加到Migrations文件夹中,您将看到一个
Up
方法与几个语句。找到添加外键并将其删除的行。 - 在包管理器控制台中,键入
Update-Database
应用迁移。 - 对于任何新的更改,重复步骤2-4。
这是假设你还没有数据库,从头开始。
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.
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:
- In the Package Manager console, type
Enable-Migrations
- In the Package Manager console, type
Add-Migration InitialMigration
- A new migration will be added to the Migrations folder, in it you will see an
Up
method with a few statements. Find the line that adds the foreign key and remove it. - In the Package Manager console, type
Update-Database
to apply migrations. - Repeat steps 2-4 for any new changes that come in.
This is assuming you do not have a database yet and are starting from scratch.
这篇关于实体框架代码第一个外键添加指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!