Software solutions for a mobile world

Having done this and forgotten how to do it several times with Xamarin projects, I decided to document how to deploy an existing SQLite database with your project in .NET MAUI. There are loads of articles on using a SQLite database by creating it from scratch, but what if you want to deploy an existing database?

I have a SQL Server database of 120,000 quiz questions and answers, and a Windows forms applications that allows me to generate quizzes. I decided to port it to .NET MAUI so I have access to it on my phone when I am out and about (very sad I know!).

I created a .NET MAUI project and added a couple of Nuget packages.

I needed to get the data from SQL Server into my SQLite database. For this I used the excellent SQLite/SQL Server Compact Toolbox from ErikEJ. One of the options is to 'Script schema and data for SQLite' which produces a script you can then execute the script from DB Browser for SQLite to create your database and populate your data. 

I did this, created a new 'Data' folder in my project, and copied my new database into the folder. After doing this, click on the database, and in the Properties window, choose Embedded Resource for the Build Action.

This ensures it will be copied to whatever device you are deploying to, as a resource. We need to extract this from the resource, and save it to a database. I declare a 'DBPath' variable that can be used throughout the project, as well as a SQLiteConnection. 

Using Environment.SpecialFolder.LocalApplicationData ensures that the correct folder for the platform is used on all platforms - iOS, Android and Windows. 

Next we need to extract the database from the resource.

First of all we get the assembly, using System.Reflection and IntrospectionExensions. Then, using Stream, we get the QuizQuestions database from the embedded resources. We use the name of the application, and in this case, the 'Data' folder where we stored the database.

Putting a break point on the 'if' statement, and stepping through, we see that the MemoryStream has a length and capacity value, which in this case is the size of our database.

In our code, we are checking that our database doesn't exist, and only copying if we don't already have a database. You may want a more robust test if you update your database and update the app, possibly using version numbers. So if the version number changes, you can delete the old database and replace it with a new copy.

We now have a full database, and can now do any CRUD operations on it. 

I hope this helps anyone to deploy their existing SQLite databases with their applications


M: +44 (0)7860 907493




Twitter Feed