Search code examples
c#.net-coreentity-framework-coremauisqlite-net

.NET MAUI Entity Framework Core migration Issue when add new Tables and Rename


Here is necessary code segments in my program. My .NET project is .NET MAUI multiproject application. It has different projects for different platforms; WinUI, iOS, Maccatalyst, and Android too.

I'm developing this app for iOS and Windows and Android yet. In the future, I focus to develop it for Mac catalyst as well. I created its UI in Blazor by coping configuration from Blazor hybrid application and it works fine. I have complex local database so I try to integrate EF Core into my app.

It works fine. But when I updating the name of tables or adding new tables to the local database, I got table not found issue. I think issue is in migrating project. I cannot create migrations using EF Core tools because it works only for the Windows platform as I know. My local db is sqlite.

Here is the relevant code in mauiprogramextension.cs:

builder.Services.AddDbContext<LocalDatabaseContext>();

var dbContext = new LocalDatabaseContext();
dbContext.Database.EnsureCreated();
dbContext.Dispose();

Here is the local DbContext:

namespace bluelotus360.Com.MauiSupports.LocalDB
{
    public class LocalDatabaseContext : DbContext
    {
        public DbSet<IncomingStrings> IncomingStrings { get; set; }
        public DbSet<ItemComboResponses> itemComboResponses { get; set; }
        public DbSet<RequestQueueItem> RequestQueueItems { get; set; }
        public DbSet<StockAsAt> StockAsAts { get; set; }
        public DbSet<AddressMasterModel> AddressMasterModels { get; set; }
        public DbSet<ItemMasterModel> ItemMasterModels { get; set; }
        public DbSet<UserMessageObject> UserMessageObjects { get; set; }
        public DbSet<PrintQueueItem> printQueueItems { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connectionDb = $"Filename={DBPath.GetPath("erp_dbase_v1.db")}";
            optionsBuilder.UseSqlite(connectionDb);
        }
    }
}

I tried with Migrate() function, but it also throws the same error.

builder.Services.AddDbContext<LocalDatabaseContext>();

var dbContext = new LocalDatabaseContext();
dbContext.Database.Migrate();
dbContext.Dispose();

Can some one give me a detailed answer? How to configure migration better at least only for Android and Windows?


Solution

  • It's recommended to use migration using EF Core command-line tools instead of code.

    If you still want to rename the table using code, you may try the workaround below,

    dbContext.Database.ExecuteSqlRaw("alter table Incoming rename to IncomingNew");  
    

    For more info, you may refer to Managing Database Schemas