c# - 可以在 Entity Framework 中设置列顺序

标签 c# entity-framework ef-code-first entity-framework-6 ef-fluent-api

在 Entity Framework 代码优先方法中是否有任何可能的配置来设置数据库列排序......?

我所有的实体集都应该有一些公共(public)字段来保存记录信息

public DateTime CreatedAt { get; set; }
public int CreatedBy { get; set; }
public DateTime ModifiedAt { get; set; }
public int ModifiedBy { get; set; }
public bool IsDeleted { get; set; }

我想将这些字段保留在表格的末尾。是否有任何可能的 EF 配置我可以用来配置它而不是将这些字段保留在我的模型类的末尾。

最佳答案

我假设您使用的是 Entity Framework 6,因为列排序 is not yet supported在 EF 核心中。

您可以使用数据属性或 Fluent API 来设置列顺序。

要使用数据属性设置列顺序,请引用 System.ComponentModel.DataAnnotations 并使用 ColumnAttribute .如果您希望它与属性名称不同,您还可以使用此属性设置列名称。

[Column("CreatedAt", Order=0)]
public DateTime CreatedAt { get; set; }
[Column("CreatedBy", Order=1)]
public int CreatedBy { get; set; }

请注意订单参数是从零开始的。

另请参阅:http://www.entityframeworktutorial.net/code-first/column-dataannotations-attribute-in-code-first.aspx

或者,您可以在 DbContext 类的 OnModelCreating 方法中使用 Fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //Configure Column
    modelBuilder.Entity<EntityClass>()
                .Property(p => p.CreatedAt)
                .HasColumnOrder(0);
}

另请参阅:http://www.entityframeworktutorial.net/code-first/configure-property-mappings-using-fluent-api.aspx

这种方式有点冗长,但您可以更好地控制正在发生的事情。

关于c# - 可以在 Entity Framework 中设置列顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43246727/

相关文章:

c# - EF 4.3 代码优先 : Table per Type (TPT) with Composite Primary Key and Foreign Key

c# - EF : Avoiding multiple update statements

c# - 我如何在 C# 中模拟 CTRL+C

c# - 10,000 多条 html 记录可快速呈现

c# - 无法加载文件或程序集 'Newtonsoft.Json,版本 = 10.0.0.0

javascript - 是否有类似于 JavaScript 中的 .Map() 的 C# 函数?

c# - 如何删除对象而不在 EF 中检索它

entity-framework - 使用 ADO.NET Entity Framework 拦截实体保存

c# - 每个表只允许一个标识列

c# - 从存储帐户 blob 读取和解析 Azure IoT 中心遥测