3

I'm trying to use 2 contexts on the same database.
To create the database I'm using DbContext.Database.EnsureCreated()
The first EnsureCreated call works fine, the second EnsureCreated call does not work.

Some considerations

Profiling SQL Server I can see that EF Core checks for the existence of a table

IF EXISTS (
        SELECT 
            * 
        FROM 
            INFORMATION_SCHEMA.TABLES 
        WHERE 
            TABLE_TYPE = 'BASE TABLE') 

    SELECT 1 
ELSE 
    SELECT 0

then it runs the create table statement.
If there is a user table on the DB nothing is done...

Is there a way to force table creations from entities scaffolding?

2 Answers 2

3

Actually I found only this way.

RelationalDatabaseCreator databaseCreator = 
    (RelationalDatabaseCreator) context.Database.GetService<IDatabaseCreator>();
databaseCreator.CreateTables();
Sign up to request clarification or add additional context in comments.

4 Comments

What about InMemoryDatabaseCreator?
What if you have multiple DbContexts, each for its separate database schema AND there are cross-schema references between tables with foreign keys? You would have to call CreateTables() on both DbContexts, but because there are cross-schema references between them, it would try to create the same table two times which results in an exception.
@samcarlson, did you find a solution to that issue?
@SoraTeichman Take a look at this GitHub issue: github.com/dotnet/efcore/issues/30844#issuecomment-1539946766
1

In my case it was because I failed to run add-migration SecondContext_Initial -Context SecondContext so there was no migration to run. Both EnsureCreated() (returned false) and Migrate() (did nothing) failed to yield any clues to my neglect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.