Reputation: 693
My migration for my SqLite database is throwing an error:
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'ProductDbContext'.
---> System.MissingMethodException: No parameterless constructor defined for type 'WpfApp1.Data.ProductDbContext'.
Here is my DbContext
public class ProductDbContext : DbContext
{
#region Constructor
public ProductDbContext(DbContextOptions<ProductDbContext> options) : base(options)
{
Database.EnsureCreated();
}
#endregion
#region Public properties
public DbSet<Product> Products { get; set; }
public DbSet<Category> Types { get; set; }
#endregion
#region Overridden methods
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new ProductDbConfig());
modelBuilder.ApplyConfiguration(new CategoryDbConfig());
modelBuilder.Entity<Product>().HasData(GetProducts());
base.OnModelCreating(modelBuilder);
}
private Product[] GetProducts()
{
// create seed data
}
}
I have an App.xaml.cs where I do my configuration
public partial class App : Application
{
#region Private members
private readonly ServiceProvider serviceProvider;
#endregion
#region Constructor
public App()
{
ServiceCollection services = new ServiceCollection();
services.AddDbContext<ProductDbContext>(options =>
{
options.UseSqlite("Data Source = Product.db");
});
services.AddSingleton<MainWindow>();
serviceProvider = services.BuildServiceProvider();
}
#endregion
#region Event Handlers
private void OnStartup(object s, StartupEventArgs e)
{
var mainWindow = serviceProvider.GetService<MainWindow>();
mainWindow.Show();
}
#endregion
}
I tried adding a parameterless constructor in my dbContext. Didn't work. What is that causes this error? And how to solve this? Any help is appreciated!
Upvotes: 0
Views: 447
Reputation: 2792
In my Xamarin.Forms application I use it this way inside the DbContext class
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Specify that we will use sqlite and the path of the database here
var options = optionsBuilder
.UseSqlite($"Data Source={SQLiteDatabasePath}");
base.OnConfiguring(options);
}
== EDIT ==
Singleton construction in my base class for all services:
private static ETabberDb _DbContext;
protected ETabberDb ETabberDbContext
{
get
{
if (_DbContext == null)
{
var dbPath = DeviceService.GetSQLiteDatabasePath();
if (!File.Exists(dbPath))
{
File.Create(dbPath).Dispose();
new SQLite.SQLiteConnection(dbPath).Dispose();
}
ETabberDb.SQLiteDatabasePath = dbPath;
_DbContext = new ETabberDb();
}
return _DbContext;
}
}
Upvotes: 1