jeudi 28 janvier 2016

Cannot resolve DbContext constructor - database creation error

In my code the EF7 is not creating the actual proper sqlite database. I'm assuming one root for the problems could be the following error, first the code snippet:.

public class Database : DbContext
{ 
    public Database()
        : base("Database")
    {
    }

    public virtual DbSet<Device> Devices { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "test2.sqlite" };
        var connectionString = connectionStringBuilder.ToString();
        var connection = new SqliteConnection(connectionString);

        optionsBuilder.UseSqlite(connection);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

I'm using WPF and entity framework 7 with Sqlite. The error which I'm receiving while trying to compile the code is as follows:

Cannot resolve constructor 'DbContext(string)', candidates are: DbContext(Microsoft.Data.Entity.Infrastructure.DbContextOptions) (in class DbContext) DbContext(System.IServiceProvider) (in class DbContext)

I'm calling the database in MainWindow.xaml.cs

public partial class MainWindow : Window
{
    private Database _context = new Database();
    public MainWindow()
    {
        InitializeComponent();
    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _context.Devices.Add(new Device
        {
            ProductCode = "100",
            TimeCreated = DateTime.Now
        });
        _context.SaveChanges();
        System.Windows.Data.CollectionViewSource deviceViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("DeviceViewSource")));

        //_context.Devices.Include(d => d.Name).Load();
        //deviceViewSource.Source = _context.Devices.GetLocal();
        //deviceViewSource.Source = _context.Categories.GetLocal();
    }

My code compiles without the :base("Database") definition but even if the *.sqlite file is created, it does not have any tables and throws this exception:

"SQLite Error 1: 'no such table: Device'"

Table configuration code I left out of this question, can add it if needed. Plain console test application works without problems.

Aucun commentaire:

Enregistrer un commentaire