在 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; }
请注意订单参数是从零开始的。
或者,您可以在 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/