Change SQL Server database alphabetic column ordering in Entity Framework code-first to sequential

浪子不回头ぞ 提交于 2020-02-03 09:31:07

问题


I need to turn off alphabetic ordering in code first.

Here is my class simplified

public class Person
{
    [Key,Column("PersonId")]
    public int Id { get; set; }
    [MaxLength(50)]
    public string PersonName{ get; set; }
    public DateTime? JoinDate{ get; set; }
    public int? Gender{ get; set; }
}

and when I run the commands to generate the database

dnx ef migrations add InitialMigration
dnx ef  database update

The database columns apart from the primary key generates in alphabetic order when I view it in design mode in SQL Server 2012.

How do I force it to create the columns in sequential order as it appears in the class.

I had a look on github and could only find this issue which doesn't explain how to turn it off.


回答1:


There is no first-class support for this behavior in EF7 migrations. You can workaround this by explicitly specifying SQL your migration operations.

That means instead of using the "CreateTable" method in your migrations, you need to explicitly write the SQL.

migrationBuilder.Sql("CREATE TABLE Person ...");



回答2:


If you are looking for column order, I think its pretty easy. In your DbContext class, override OnModelCreating. Then grab modelBuilder, and from it pull out EntityTypeConfiguration. Then using it configure the order as follows.

public class AppDbContext : IdentityDbContext<AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
    public AppDbContext() : base("AvbhHis")
    {

    }

    public DbSet<PatientCategory> Product { get; set; }
    public DbSet<LookupBase> LookupBase { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder
            .Entity<PatientCategoryLookup>()
            .Map<PatientCategoryLookup>(m =>
            {
                m.ToTable("LookupPatientCategory");
                m.MapInheritedProperties();
            });
        EntityTypeConfiguration<PatientCategoryLookup> config = modelBuilder.Entity<PatientCategoryLookup>();
        config.Property(e => e.Id).HasColumnOrder(0);
        config.Property(e => e.PatientCatgCode).HasColumnOrder(1);
        config.Property(e => e.PatientCatgName).HasColumnOrder(2);
        config.Property(e => e.Description).HasColumnOrder(3);
        config.Property(e => e.ModifiedTime).HasColumnOrder(4);
        config.Property(e => e.History).HasColumnOrder(5);

        base.OnModelCreating(modelBuilder);
    }

}

And then ofcourse you need to add migration and then update database.



来源:https://stackoverflow.com/questions/33752065/change-sql-server-database-alphabetic-column-ordering-in-entity-framework-code-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!