可以在Entity Framework中设置列排序

问题描述 投票:6回答:2

是否有任何可能的配置来设置实体框架代码中的数据库列排序第一种方法..?

我的所有实体集都应该有一些用于保存recordinfo的公共字段

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配置可用于配置此配置,而不是将此字段保留在我的模型类的末尾。

c# entity-framework ef-code-first entity-framework-6 ef-fluent-api
2个回答
5
投票

我假设您正在使用Entity Framework 6,因为在EF Core中排序is not yet supported

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

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

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

请注意,Order参数从零开始。

另见: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

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


0
投票

只需使用:

using System.ComponentModel.DataAnnotations.Schema;

码:

[DisplayColumn("Name" , Order = 1)]
public int UserName { get; set; }

注意:默认情况下,列顺序需要一个大数字,因此如果您只订购此列,它将是表中的第一个,除非您订购了另一个具有较低订单号的列,在这种情况下:0

© www.soinside.com 2019 - 2024. All rights reserved.