最近在用codesmith操作写access数据库的代码模版,发现codesmith默认的字段顺序与access中表的字段顺序不一致。 首先在access数据库中建一个测试表test,并添加id、name等几个字段,如下图所示: 然后在codesmith中新建一个模版,并循环输出所有字段名 %@ cod
最近在用codesmith操作写access数据库的代码模版,发现codesmith默认的字段顺序与access中表的字段顺序不一致。
首先在access数据库中建一个测试表test,并添加id、name等几个字段,如下图所示:
然后在codesmith中新建一个模版,并循环输出所有字段名
c# targetlanguage=c# responseencoding=utf-8%>sourcetable type=schemaexplorer.tableschema category=context description=数据表 %>schemaexplorer %>schemaexplorer %>for(int i=0;i
运行后得到
ageidisoknameremarktime
我们可以看到,字段是按照字典顺序排序的,而不是实际数据表中的顺序。虽然这不影响什么,但是一想到自动生成的model层的字段和数据表的不对应,总感觉不太爽。
我甚至将sourcetable.columns[i].extendedproperties这个扩展属性全部输出,也没有得到什么有用的信息。
后来无意中,我在.net的 oledbconnection.getoledbschematable中得到了字段的顺序,新建一个winform项目,代码如下
1 string accessconnection = provider=microsoft.jet.oledb.4.0;jet oledb:database password=123456;data source=c:\\db1.mdb;persist security info=true;2 oledbconnection connection = new oledbconnection(accessconnection);3 connection.open();4 datatable schemacolumns = connection.getoledbschematable(oledbschemaguid.columns, new string[] { null, null, test, null });5 datagridview2.datasource = schemacolumns;6 connection.close();
我将getoledbschematable获取到信息都绑定到一个datagridview控件中,这样对里面的数据可以有一个比较直观的了解
终于看到了字段真正顺序!那么接下来的事情就比较好办了,我们要在codesmith中获取这个schematable,然后根据ordinal_position的值重新对sourcetable.columns进行排序,这样后面编写代码模版的时候,字段顺序就是正常的了。codesmith代码如下:
c# targetlanguage=c# responseencoding=utf-8%>sourcetable type=schemaexplorer.tableschema category=context description=数据表 %>schemaexplorer %>schemaexplorer %>system.data.oledb %>for(int i=0;i
代码不难理解,我用了类似插入排序的思路,从排序最后的字段开始往前查找(即ordinal_position值从最大到最小),查找到了后就插入到sourcetable.columns集合的最前面。这样到最后的结果就是sourcetable.columns集合按ordinal_position值从小到大排序了。
