How to use code first and data migration with ServiceStack.OrmLite

ntroduction

ServiceStack.OrmLite is an Open Source, Fast, Simple, Typed ORM for .NET, the performance is better than EntityFramework and more flexible. You can find more detail in their GitHub site.

And in this article, I will show you how to do the code first with OrmLite and keep the data.

Background

So, I want to try to instead of EntityFramework with OrmLite, but by default, OrmLite’s code first just can work in first time for initialize the project, because it will delete all of the data and re-create the table structure every time, that’s mean it can’t migrate the data when the project is running, but don’t worry, I will show you how can solve this problem 🙂

3. We have created another independent console project for data migration, so we need to pass below information by app.config file:

1) UpdateAll: whether update all tables 2) UpdateTables: Which’s tables need to be update, split with comma and just will do when UpdateAll is false. (Sometime we may just want to udpate several tables) 3) ModelNamespace: The Model project’s namespace, we can dynamic update the table and fields by this, so why need an independent Model project

app.config file:

<appSettings>
<!--Update all tables-->
<add key="UpdateAll" value="true" />
<!--Which's tables need to be update, split with comma and just will do when UpdateAll is false-->
<add key="UpdateTables" value="Page" />
<!--Code first Model for generate the tables in database-->
<add key="ModelNamespace" value="CoderBlog.Model" />
</appSettings>

4. We need to dynamic get the models for create table and columns, so we can use dynamic load the model by Assembly.Load(that’s why we need to create an independent model project)

But in my case, we need to dynamic to do that, and we have get the model objects by Assembly before , so in this time we need to dynamic call the method. We created a Migration class and a method for UpdateTable :