EntityFramework 代码优先:设置字段顺序

EntityFramework code first: Set order of fields

我正在使用 EntityFramework 和 "Code first" 迁移方法。

我已经成功地从我的模型中生成了表格,但是这些列是按字母顺序添加的,而不是我模型中的顺序。

我试过这个:

[Key, Column(Order=0)]
public int MyFirstKeyProperty { get; set; }

[Column(Order=1)]
public int MySecondKeyProperty { get; set; }

但这似乎不起作用。

如何手动设置数据库中字段的顺序?

我正在使用 ASP.NET Core 和 EF Core (SqlServer) v1.1.0。

目前未实现按 class 属性 对列进行排序。 这是关于列排序的长期讨论。 Column ordering #2272

Update as of 07/12/2017

This issue is in the Backlog milestone. This means that it is not going to happen for the 2.0 release. We will re-assess the backlog following the 2.0 release and consider this item at that time.

Update as of 06/10/2019

问题 2272 随 EF Core v2.1 一起提供,并将生成的 table 中的列顺序与 class 中的属性顺序相匹配。但是,正如@lloyd-conrade 提到的,这仅对初始创建有用

已创建一个新问题 #10059 来跟踪尊重 Column 属性的顺序的可能实现 属性。

If the implementation of #2272 is insufficient for you and specifying something like [Column(Order = 1)] would help, please vote for this issue and add details about your scenario (if not already listed) below.

请注意,"Punted for 3.0" 标签是在 2019 年 5 月 10 日添加的,也就是说它将不会在 EF Core 3.0 中发布。

此时 EF 核心不支持它。但是 that.That 有一个解决方法是,您可以在您的迁移操作。

不要在迁移中使用 CreateTable 方法,您需要显式编写 SQL,如图所示 below.There 您可以根据需要给出命令。

migrationBuilder.Sql("CREATE TABLE Properties(
   MyFirstKeyProperty   INT   NOT NULL,
   MySecondKeyProperty int    NOT NULL,
   AGE  INT   NOT NULL,
   ......
   ......   
   PRIMARY KEY (MyFirstKeyProperty)
)");

您可以阅读有关 rowanmiller's commnet here about how to sort out that issue just for now

更新:在 EF Core 2.1 中,至少对于初始迁移,列是按照相关属性在其各自 类 中声明的顺序添加到表中的,而不是按字母顺序。参见 here。但请注意,对相同表执行的任何后续 Entity Framework 迁移都不会更改先前创建的列的列顺序。

您可以使用此解决方案为您的项目添加对显式列排序的支持:https://github.com/premchandrasingh/EFCoreColumnOrder。此解决方案添加了 HasColumnOrder 扩展方法。 Sample文件夹中有使用示例。不要忘记在你的 DbContext 中替换相应的服务。

您提到的列的顺序用于指定复合外键列的顺序,因为在某些表中有两个或多个字段作为引用其他表的外键的情况下,在这种情况下,您可以使用 Column (Order = n)

从 Entity Framework 核心 6 开始,您可以使用注释指定列顺序:

[Column(Order = 1)]
public int Id { get; set; }

https://docs.microsoft.com/en-us/ef/core/modeling/entity-properties?tabs=data-annotations%2Cwithout-nrt#column-order