迁移EF Core中的订单列

时间:2019-04-19 06:45:30

标签: c# entity-framework ef-migrations ef-core-2.0

'我正在开发一个EF Core应用程序,该应用程序在entity中继承了一个公共类。当我迁移和更新数据库时,首先会创建继承的列,然后是实体的属性。

很好奇,我想知道是否可以自动设置SQL表中列创建顺序的方式。

//代码:

public class Employee: BasicEntity
{
    [Required(ErrorMessage = "Name is required")]
    [StringLength(60, ErrorMessage = "Name can't be longer than 60 characters")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Age is required")]
    public int Age { get; set; }

    [Required(ErrorMessage = "DOB is required")]
    public DateTime DOB { get; set; }

    [Required(ErrorMessage = "City is required")]
    public int City { get; set; }

    [Required(ErrorMessage = "State is required")]
    public int State { get; set; }

    [Required(ErrorMessage = "Country is required")]
    public int Country { get; set; }

}

2 个答案:

答案 0 :(得分:0)

您可以使用[Column(Order =)]将数据注释用于EF核心中的列顺序

public class Employee: BasicEntity
    {
        [Column(Order=0)]
        [Required(ErrorMessage = "Name is required")]
        [StringLength(60, ErrorMessage = "Name can't be longer than 60 characters")]
        public string Name { get; set; }

        [Column(Order=1)]
        [Required(ErrorMessage = "Age is required")]
        public int Age { get; set; }

        [Column(Order=2)]
        [Required(ErrorMessage = "DOB is required")]
        public DateTime DOB { get; set; }

        [Required(ErrorMessage = "City is required")]
        public int City { get; set; }

        [Required(ErrorMessage = "State is required")]
        public int State { get; set; }

        [Required(ErrorMessage = "Country is required")]
        public int Country { get; set; }



    }

答案 1 :(得分:0)

不幸的是,EF Core不支持显式列排序。关于此问题有很多讨论:https://github.com/dotnet/efcore/issues/2272

您可以使用此解决方案为您的项目https://github.com/premchandrasingh/EFCoreColumnOrder添加对显式列顺序的支持。此解决方案添加了HasColumnOrder扩展方法。 Sample文件夹中有一个使用示例。不要忘记替换DbContext中的相应服务。

此外,您可以在EF迁移中以正确的顺序手动排列列。