有什么方法可以在.net核心的OnModelCreating中的table中使用order by子句

Is there any way to use order by clause in the table inside OnModelCreating in .net core

我想在下面的代码中使用 order by 子句。模型和视图中有 StartDatetime 字段。所以order by应该在代码中使用startDatetime desc。 谁能指导我如何操作?

  protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            {
                var builder = modelBuilder.Entity<TestBookingsView>().ToTable("vw_Testbooking");
 
                SetKey(builder);
            }

            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }

重写 OnModelCreating 方法以进一步配置根据约定从派生上下文的 DbSet 属性中公开的实体类型发现的模型。

在OnModelCreating方法中,我们可以使用Fluent API配置Model、Entity和属性Configuration。示例代码如下:

public class SchoolDBContext: DbContext 
{
    public DbSet<Student> Students { get; set; }
        
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Write Fluent API configurations here

        //Property Configurations
        modelBuilder.Entity<Student>()
                .Property(s => s.StudentId)
                .HasColumnName("Id")
                .HasDefaultValue(0)
                .IsRequired();
    }
}

有关使用 Fluent API 的更多详细信息,请查看以下文章:

Fluent API in Entity Framework Core

Fluent API Configuration

I want to use the order by clause in the code below. The model and the View have StartDatetime field in it. So the order by should use startDatetime desc in the code.

根据您的描述,我假设您可能想使用 Fluent API 设置默认顺序。在EF 6中,使用Fluent API时有一个HasColumnOrder() method,但不幸的是,在EF core中,似乎不支持此方法。

所以,我建议你可以使用 OrderBy or OrderByDescending methods in the Query statement, instead of in the OnModelCreating method. You can refer this tutorial:Tutorial: Add sorting, filtering, and paging - ASP.NET MVC with EF Core