问题
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