Search code examples
c#servicestackormlite-servicestack

Columns Physical Order in OrmLite


regards everybody:

I have a data model for example:

    [Alias("log")]
    public class Log
    {
        [AutoIncrement]
        [PrimaryKey]
        [Alias("id")]
        public int Id { get; set; }

        [Required]
        [Alias("user_id")]
        [Index(Name = "user_id", Unique = false)]
        [ForeignKey(typeof(User), ForeignKeyName = "log_fk", OnDelete = "CASCADE", OnUpdate = "CASCADE")]
        public int UserId { get; set; }
        
        [Required]
        [StringLength(255)]
        [Alias("action")]
        public string Action { get; set; }

        [Required]
        [Alias("body")]
        [CustomField("TEXT")]
        public string Body { get; set; }
    }

but when executing my command:

db.CreateTableIfNotExists<Log>();

The columns order in MariaDb database not is the same, the columns that use the CustomField attribute se colocan to next to Id column.

Exists any method to specify the order explicit of columns in the class so it works, I tried with [DataMember(Order = x)] and [Priority(x)], and not work.

Thanks in advance.


Solution

  • The [CustomField] attribute has an Order property which controls the ordering of columns, so you can sort Body column last with:

    [Alias("log")]
    public class Log
    {
        [AutoIncrement]
        [PrimaryKey]
        [Alias("id")]
        public int Id { get; set; }
    
        [Required]
        [Alias("user_id")]
        [Index(Name = "user_id", Unique = false)]
        public int UserId { get; set; }
    
        [Required]
        [StringLength(255)]
        [Alias("action")]
        public string Action { get; set; }
    
        [Required]
        [Alias("body")]
        [CustomField("TEXT", Order = 4)]
        public string Body { get; set; }
    }     
    

    For more precise control you can override the column resolution behavior by returning a custom field order with:

    MySqlDialect.Instance.CreateTableFieldsStrategy = modelDef =>
    {
        var origOrder = modelDef.FieldDefinitions.OrderBy(x => x.Order);
        // sort origOrder
        return origOrder;
    };