|
| 1 | +--- |
| 2 | +title: "Use of Sqlite in Maui" |
| 3 | +author: "PrashantUnity" |
| 4 | +weight: 106 |
| 5 | +date: 2025-06-19 |
| 6 | +lastmod: 2024-06-19 |
| 7 | +dateString: July 2025 |
| 8 | +description: "Code snippet for maui sqlite implementation" |
| 9 | +#canonicalURL: "https://canonical.url/to/page" |
| 10 | +cover: |
| 11 | + image: "cover.jpg" # image path/url |
| 12 | + alt: "Download Logo" # alt text |
| 13 | + #caption: "Optical Character Recognition" display caption under cover |
| 14 | + |
| 15 | +tags: [ "NET", "codefrydev", "C sharp", "CFD","maui" , "controls","entry"] |
| 16 | +keywords: [ "NET", "codefrydev", "C sharp", "CFD","maui" , "controls"] |
| 17 | +--- |
| 18 | + |
| 19 | +## Step to implement |
| 20 | + |
| 21 | +### Install/ Add Microsoft.EntityFrameworkCore.Sqlite to Project |
| 22 | + |
| 23 | +```xml |
| 24 | + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.7" /> |
| 25 | +``` |
| 26 | + |
| 27 | +### Register App db Context before `var app = builder.Build();` in MauiProgram.cs |
| 28 | + |
| 29 | +```cs |
| 30 | +var dbPath = Path.Combine(FileSystem.AppDataDirectory, "waterreminder.db3"); |
| 31 | + |
| 32 | +builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlite($"Filename={dbPath}")); |
| 33 | +``` |
| 34 | + |
| 35 | +### Just Before app run add this Command |
| 36 | + |
| 37 | +```cs |
| 38 | +// Initialize the database |
| 39 | +using (var scope = app.Services.CreateScope()) |
| 40 | +{ |
| 41 | + var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>(); |
| 42 | + dbContext.Database.EnsureCreated(); |
| 43 | +} |
| 44 | + |
| 45 | +return app; |
| 46 | +``` |
| 47 | + |
| 48 | +### Create Add Db Context |
| 49 | + |
| 50 | +```cs |
| 51 | +namespace WaterReminder.Data; |
| 52 | + |
| 53 | +public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options) |
| 54 | +{ |
| 55 | + public DbSet<Reminder> Reminders { get; set; } |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | +### Below is service or uses |
| 60 | + |
| 61 | +```cs |
| 62 | +public class ReminderService : IReminderService |
| 63 | +{ |
| 64 | + private readonly AppDbContext _context; |
| 65 | + |
| 66 | + public ReminderService(AppDbContext context) |
| 67 | + { |
| 68 | + _context = context; |
| 69 | + } |
| 70 | + |
| 71 | + public Task<List<Reminder>> GetRemindersAsync() => _context.Reminders.ToListAsync(); |
| 72 | +} |
| 73 | +``` |
0 commit comments