Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column Order EF Core with inheritance

I Have an EF Core 3.1 code first project in which most classes inherit from a common base class named BusinessObject.

public abstract class BusinessObject
{    
    [Required()]
    [Column("Id", Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column("Comment", Order = 100)]
    public string Comment { get; set; }

    [Required()]
    [Column("CreatedAt", Order = 101)]
    public DateTimeOffset CreatedAt { get; set; } = DateTime.UtcNow;

    [Required()]
    [Column("CreatedByUserId", Order = 102)]
    public int CreatedByUserId { get; set; }           

    //A few more columns....
}

[Table("MyTable", Schema = "SampleSchema")]
public class MyTable: BusinessObject
{
    [Column("MyColumns1", Order = 1)]
    [MaxLength(256)]
    public string MyColumns1{ get; set; }

    [Column("MyColumns2", Order = 2)]
    [MaxLength(256)]
    public string MyColumns2{ get; set; }
}

As you can see, I want to set the order of the columns by data annotations and I would expect a table to be created like this:

  • Id
  • MyColumns1
  • MyColumns2
  • Comment
  • CreatedAt
  • CreatedByUserId

In reality, the migration does

  • Id
  • Comment
  • CreatedAt
  • CreatedByUserId
  • MyColumns1
  • MyColumns2

What am I missing? Is this possible by Fluent API? I prefer data annotations to keep the DBContext lean.

like image 742
Ned Flanders Avatar asked Nov 17 '19 23:11

Ned Flanders


2 Answers

Although this is an old thread, this is exactly the same issue that I am having too and may be resolved using the code as suggested in this link here

https://github.com/premchandrasingh/EFCoreColumnOrder

which stems from reported problems on git hub here

https://github.com/dotnet/efcore/issues/2272

It is suggested that this issue is fixed in core 2.0, however there is a proportion of people saying and confirming that this is not the case, thus leading to using the custom implementation.

like image 85
Simon Price Avatar answered Sep 21 '22 02:09

Simon Price


In NET 5.0 RC2, the “order” attribute works!

like image 29
Giacomo Policicchio Avatar answered Sep 25 '22 02:09

Giacomo Policicchio