在CodeSmith中,如果生成的代码是SQL脚本,则可以在生成代码完成时自动执行生成的代码,也就是在生成的SQL脚本的同时在数据库中创建新的对象。
用BaseTemplates.ScriptUtility对象提供ExecuteScript方法可以实现,如果想在生成代码完成后立即执行生成的脚本,可以很方便的通过重载OnPostRender来实现。
在使用之前,先添加对下列程序集的引用:
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
看下面的这个例子:
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://terrylee.cnblogs.com/Images/OutliningIndicators/None.gif)
在这个例子中SourceTable是一个类型为SchemaExplorer.TableSchema.的属性,使用的时候需要调整部分代码来获取数据库的连接以便在生成代码完成后执行脚本。