context.EnsureCreated() throwing exception - already a table named

c# entity-framework-core sqlite


Creating unit tests with Sqlite InMemory is giving exceptions with and without EnsureCreated(). I'm testing on the MS Northwind database.

If I call ensureCreated() is throws an exception "Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'there is already a table named Region'."

My understanding is that EnsureCreated() will only attempt to create the database if it is not already created.

It looked like it had therefore already created the DB, so I tried removing that call which resulted in an exception later because the tables didn't exist. So, I get exceptions with EnsureCreated() and no tables without it.

I have already checked the context.OnModelCreating and the table 'Region' is only defined once.

Note that this works fine running on an existing SQL database and also allowing EFCore to create a new SQL database. The problem only exists with sqlite in-memory mode.

public async Task UpdateCategoryWithCorrectEtag(Category expectedCategory)
       var connection = new SqliteConnection("DataSource=:memory:");
       var builder = new DbContextOptionsBuilder<NorthwindContext>().UseSqlite(connection);
       var context = new NorthwindContext(builder.Options);

           var x = context.Categories.Count();

EDIT: The 'Region' entity defined as follows. I also note that this seems to be the only table where the Entity name already matches the table name.

modelBuilder.Entity<Region>(entity =>
    entity.HasKey(e => e.RegionId)

    entity.Property(e => e.RegionId)

    entity.Property(e => e.RegionDescription)

UPDATE: I already tried removing the line entity.ToTable("Region"); to see if that was causing the table to be created twice, however, this still has the same problem. Currently I've removed all tables except for the 2 I absolutely need to run the test and it works. Putting them back in one by one to see what breaks. Will report back.

5/30/2019 2:45:22 PM

Accepted Answer

I have the answer after spending more time removing all tables and then adding items until the problem returned.

The problem was caused by indexes on tables being the same as indexes on other tables, or as a table name. With SQL Server and EF Core in-memory, this was OK because it saw them as indexes on the table. But, with Sqlite, it wasn't happy about different objects having the same name, regardless of their apparent scope.

The solution was to ensure that all objects' names were unique so nothing clashed at all. In this case, the name 'Region' was the name of a table and the name of an index on a different table.

5/30/2019 3:32:40 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow