-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathBloggingContext.cs
More file actions
45 lines (37 loc) · 1.5 KB
/
BloggingContext.cs
File metadata and controls
45 lines (37 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace ConsoleApp.SQLite
{
public class BloggingContext : DbContext
{
public const string DEFAULTDBFILE = "blogging.db";
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
private readonly string dbFile = DEFAULTDBFILE;
private SqliteConnection connection;
public BloggingContext() { }
public BloggingContext(string databaseFile)
{
if(!string.IsNullOrEmpty(databaseFile)) dbFile = databaseFile;
}
public BloggingContext(SqliteConnection sqliteConnection)
{
if (!string.IsNullOrEmpty(sqliteConnection?.DataSource)) dbFile = sqliteConnection.DataSource;
connection = sqliteConnection;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
connection ??= InitializeSQLiteConnection(dbFile);
optionsBuilder.UseSqlite(connection);
}
private static SqliteConnection InitializeSQLiteConnection(string databaseFile)
{
var connectionString = new SqliteConnectionStringBuilder
{
DataSource = databaseFile,
Password = "Test123"// PRAGMA key is being sent from EF Core directly after opening the connection
};
return new SqliteConnection(connectionString.ToString());
}
}
}