EF6 + Postgres relation dbo.AspNetUsers does not exist - entity-framework

I have been following this post on using PostgreSQL with EF6 http://www.jasoncavett.com/blog/postgresql-and-entity-framework-6-code-first/.
I have started a brand new MVC5 project hoping to use Postgres in my application for backend. The application starts up fine however when you go to register a user (I selected individual authentication) I get the following error messsage
ERROR: 42P01: relation "public.AspNetUsers" does not exist
I am unsure as to how to resolve this problem.
The error happens on line 155 which can be seen here
More information can be provided if needed.

I had ran the application before migrating to Postgres so all I needed to was to add a migration and update database through the package manager console.

If you see this Error in 2018, the answer is because the table has not being added to the migrations.
dotnet ef migrations add 01_users &&
dotnet ef database update

It is interesting but when i write as below it works on tableplus;
select *
from "AspNetUsers";
or
select "UserName"
from "AspNetUsers";

Related

How to fix 'CREATE SCHEMA' failed error when running EF Code First migrations with Azure Managed Identity

I am trying to run EF6 Code First migrations against an Azure SQL database connecting via Azure Managed Identity. There are several migrations to run. The last migration fails. This migration is different to the others because it creates tables in a new schema.
This is the error which is returned when running the Entity Framework Code First migration which creates the new schema:
System.Data.SqlClient.SqlException: The specified schema name "uuid#uuid" either does not exist or you do not have permission to use it.
CREATE SCHEMA failed due to previous errors.
I have logged the SQL commands on the database and the command which appears to be failing is
IF schema_id('MyNewSchema') IS NULL
EXECUTE('CREATE SCHEMA [MyNewSchema]')
With the error:
<batch_information><failure_reason>Err 2759, Level 16, Server mysqldbname
CREATE SCHEMA failed due to previous errors.</failure_reason></batch_information>
Here are some details on the system:
All other migrations before this one succeeded. However, none of those needed to create a new schema
Using .NET Framework 4.7.1. EF6.2.0.
Using Azure SQL database.
Connecting to Azure SQL from an ASP.NET MVC web application using Azure Managed Identity (https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi).
Things I've tried
1. Adding roles
The main thing I've tried is using the Microsoft permissions docs to work out what permissions are needed. So far I have added the following roles to the contained user which the App Service running migrations connects as:
db_ddladmin
db_datareader
db_datawriter
db_securityadmin
db_owner
db_accessadmin
(Note that the other migrations worked fine with just db_ddladmin, db_datareader and db_datawriter)
2. Running migrations as server admin
I have tried running the migrations as the SQL Server admin user. This works, but we are not allowed to connect as the SQL Server admin user for the production system.
If you add AUTHORIZATION to the CREATE SCHEMA command, it works.
So the statement Entity Framework creates need's to look like this instead:
IF schema_id('MyNewSchema') IS NULL
EXECUTE('CREATE SCHEMA [MyNewSchema] AUTHORIZATION [dbo]')
You can do this by overwriting ApplicationSqlServerMigrationsSqlGenerator
protected override void Generate(EnsureSchemaOperation operation, IModel model, MigrationCommandListBuilder builder)
{
if (operation is null)
throw new ArgumentNullException(nameof(operation));
if (builder is null)
throw new ArgumentNullException(nameof(builder));
if (string.Equals(operation.Name, "dbo", StringComparison.OrdinalIgnoreCase))
{
return;
}
var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string));
builder
.Append("IF SCHEMA_ID(")
.Append(stringTypeMapping.GenerateSqlLiteral(operation.Name))
.Append(") IS NULL EXEC(")
.Append(
stringTypeMapping.GenerateSqlLiteral(
"CREATE SCHEMA "
+ Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)
+ " AUTHORIZATION "
+ Dependencies.SqlGenerationHelper.DelimitIdentifier("dbo")
+ Dependencies.SqlGenerationHelper.StatementTerminator))
.Append(")")
.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator)
.EndCommand();
}
And then registering it:
services.AddDbContextPool<ApplicationDbContext>(options =>
{
options.UseSqlServer("Your connection string");
options.ReplaceService<IMigrationsSqlGenerator, ApplicationSqlServerMigrationsSqlGenerator>();
});
(The code above is for EF Core, as I had the issue there)
I've just run into the same issue using asp.net core 2.2 and EF core. I was trying to use a managed identity to create the schema and got the same error. I found this article which indicates it is a bug - https://techcommunity.microsoft.com/t5/Azure-Database-Support-Blog/Lesson-Learned-54-The-specified-schema-name-name-domain-com/ba-p/369152.
My only workaround has been to create the schema with server admin which isn't ideal.

Entity Framework core won't update database

I successfully created an Entity Framework Core migration and updated the database with it.
Then after I added another class, I created a second migration called "update1" which created a class of the same name from the command line tools.
However, when I attempt to update the database, it fails.
Here is the commands I used
dotnet ef migrations add update1 -c MyDbContext
dotnet ef database update update1 -c MyDbContext
and it failed with
There is already an object named MyTable in the database
which is a table which was created in the initial migration.
How can I tell it to either ignore the error, or else to only attempt to run the update1 migration?
Edit: deleting the table that was already there caused this odd behavior to stop happening and now it works as expected.
Thanks
You have to remove the unwanted migration from the __MigrationHistory table.After that you can run your latest migration.This is happened due to you have manually deleted the table.B'cos EF doesn't know anything about your manual operations hence __MigrationHistory table still exist your old migration details (i.e. manually deleted table's record).
In my case I used Ubuntu, EF 6 and the database was in the docker and it's doesn't updated DB.
I added --connection attribute and it's works, an example:
sudo dotnet ef database update --connection
"Server=localhost;Database=temp;User Id=sa;Password=xxxxxxx;"

EF 7 Migration to Existing Database

I am working on a web project using ASP.Net 5 and EF7.
I have imported all the tables from existing database onto my models in my project. However, I am having problems in regards with migrations.
I have created the initial migration, made some changes on particular entity, create another migration following the changes I have made and now want to apply the changes on the database.
After running this command below:
dnx ef database update [Migration]
the dnx is trying to apply the 'initial' migration with all the entities which are already in database and this causes an error as below:
{ There is already an object named ['EntityName'] in the database. }
Can you please advise on how to do the migration on the existing database?
Thanks
Saeed
In EF6 you would run a migration with the -IgnoreChanges flag and it would take a snapshot of the model without any Up() code. This is missing from EF 7(EF Core) as indicated here.
The workaround for now is delete or comment out the code for existing database objects from the Up() code of the migration and then update-database. Subsequent migrations will then include only the changes.
After 2 days I found a way for EFCore that is not in google and internet!
How My steps works?
When you have a database with 10 table and you have data in tabales that you don't want to clear's data.and after this you will create new models in your code first and runnig to existing database and you will get error "Invalid object name 'tableName'." for query to new tables and you want to create migrations and do update it to existing database but first migration will create all queries for old and new tables if you run update-database you will get "There is already an object named ['EntityName'] in the database." for your initial migration.
How fix it?
Delete all migrations and snapshot in you database project
Delete __EFMigrationsHistory table in your existing database (if exist)
Run in Package manager console:
Note before run: This code will create new context and models of your existing database to Data folder so don't forgot to check you have not Data folder in your project.
Scaffold-DbContext "your connection string"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data
Run in Package manager console:
Note before run: Create first migration for initial database with Data folder context (OldDataBaseContext is inside of your Data folder that created by step 2)
Add-Migration initial -Context OldDataBaseContext
Delete all code in Up method inside of created initial migaration in step 3
Run in Package manager console:
Note before run: Update databse with Data folder context (OldDataBaseContext is inside of your Data folder that created by step 2)
Update-Database -Context OldDataBaseContext
Delete data folder that created in Step 2
Go to snapshot and initial migration classes and change the deleted context from Data folder to main context that is exist in your database project (just fix it for build)
Run:
Note before run: Add migration for main context that have new database changes
Add-Migration newUpdate
Run:
Update-Database
I Hope this help someone.
If you are strongly believe, that new (EF7) database schema will match your old database schema (including index and key names) - you may run 'Initial' migration to empty (temporary) database and then copy __EFMigrationHistory table from there to your real database.
Otherwise, I recommend you create empty database using migration and use sql insert into ... select commands to copy data from your old database. Without this, you will receive exceptions when upgrading database later - for example changing index will lead to DropIndex and CreateIndex migration commands, and DropIndex will fail because there is no index with this name (index exist with other, pre-EF7 name).
In my projects - old (from EF6) and new database schemes are different, and I used second option.

moving to a new database with Code First Migrations

I have recently started using code first and migrations and I'm pretty happy with it.. I have been following the constant pattern of add-migration and update-database!
I have just tried to move from localdb to SQL Express and im having a real pain..
when I try and run the application.. I get the follow error..
Cannot find the object "dbo.AspNetUsers" because it does not exist or you do not have permissions.
In my Global file I have..
Database.SetInitializer(new MigrateDatabaseToLatestVersion());
Any ideas? It looks like the core forms tables are not being created?
if I run my application without the Initializer in the global file I get this.
Migrations is enabled for context 'ApplicationDbContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console.
Thanks
Ste.

Tables are not executed after validating and updating schema

I have created entities in zend framework 2 using doctrine 2. After that I used this command to validate current schema.
./vendor/bin/doctrine-module orm:validate-schema
I got output like:
Mapping] OK - The mapping files are correct.
[Database] FAIL - The database schema is not in sync with the current mapping file.
Then I executed update command,
./vendor/bin/doctrine-module orm:schema-tool:update --force
The output for that is like:
Database schema updated successfully! "7" queries were executed
But, the problem is, There is no tables created in my database. What's wrong with this?
I used to run doctrine-module orm:validate-schema and then doctrine-module orm:schema-tool:create.
Here is good project to try:
Fmi-example on github