4

When using TypeAccessor.Create FastMember always seems to return a list of the columns in alphabetic sorted order. Is it possible to tell it to preserve the ordering of the columns in the class?

for example:

var testClass = new { B = "1", A = "2" };

will return column A then B from GetMembers, I'd like to get it to preserve the ordering of B then A if possible.

gmn
  • 4,199
  • 4
  • 24
  • 46
  • Curious, why exactly you need that? – Evk Nov 16 '16 at 09:56
  • kind of like the bulk insert, but I'd like to be able to throw data into other data stores too, some of which might care about ordering. @Evk – gmn Nov 16 '16 at 11:36
  • 1
    Without heavy reflection I think you cannot do that. Deep inside FastMember library author orders properties by name and seems there is no way around it. If that is a requirement, you can either ask author to add such functionality, or not use this library at all. – Evk Nov 16 '16 at 11:47
  • Other option would be to get properties with reflection once, yourself, and then reoder result of GetMembers manually. – Evk Nov 16 '16 at 12:02
  • yeah @evk that might do the trick – gmn Nov 16 '16 at 12:23

2 Answers2

4

I created a fork of this project with column order option and added a PR to the original repository. OrdinalAttribute was added to specify columns order.

The ordinal attribute can be used as shown below:

        public class ObjectReaderWithDefinedColumnsOrderType
        {
            [Ordinal(1)]
            public byte C { get; set; }
            [Ordinal(0)]
            public int? D { get; set; }
        }
  • IDataReader object returned in ObjectReader.Create() will have columns order according to the defined attributes.
  • If the attribute is not defined in the source class then alphabetical order is used.
  • If two fields have the same Ordinal value then then alphabetical order is used.
  • If the attribute is defined only for some properties then the columns are sorted by the ordinal values and then in alphabetical order (properties with no attributes are considered as -1 ordinal).

You can use my for right away or wait until the PR is merged with the original repository.

dyatchenko
  • 2,283
  • 3
  • 22
  • 32
2

Looks like Evk is right and it can't really be done via the standard APIs. In the interest of completeness I'll leave this as the answer.

gmn
  • 4,199
  • 4
  • 24
  • 46
  • 1
    I ran into the same problem: passing a dt into a user defined table type for a stored procedure kept failing due to columns being ordered alphabetically but FastMember. Thanks for the feedback. – callisto Oct 02 '18 at 19:41