I am new to c#/.NET and developing an application with SQlite datbase and entity framework and it is all working fine during testing. I am specifying the below for the filepath to the .db file.
var path = AppDomain.CurrentDomain.BaseDirectory;
On deployment I need the application to create the database fresh, that doesn't contain the test data I was using during development. So I cannot simply copy the current .db file. Can anyone help with code that checks existence of database, and if not it will create new?
CodePudding user response:
An appliation that creates databases should be in principle a script that creates databases. If you application has its own business line which requires a database, but it is not intended to create a database at first, better you create it manually outside the code and then simply let the code choose between which database to use between testing and production, via appSettings or similar solution.
CodePudding user response:
You can use this method:
private static void CreateFreshDb(string dbFilePath)
{
// Create the DB file
SQLiteConnection.CreateFile(dbFilePath);
// Create a table
var connectionString = $"Data Source={dbFilePath};Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string creationScript = "Create Table Person (Id int, Name varchar(20))";
SQLiteCommand command = new SQLiteCommand(creationScript, connection);
command.ExecuteNonQuery();
command.Dispose();
}
}
And call it like that:
string dbFilePath = "C:\\Db\\Database.db";
if (!File.Exists(dbFilePath))
{
CreateFreshDb(dbFilePath);
}
Note that I use the System.Data.SQLite library here.