Entity Framework Core Error: dotnet.exe : System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Company' in the database - sql

I am building a application with ASP.NET Core MVC6 and Entity Framework Core code first with build in DB context, the SQL database has already been populated with data records. I recently made some small changes to the data models and recreate the migration, with commands as ("dotnet ef migrations add Stage3", "dotnet ef database update") in VS 2015 Package Manager Console, but it ran into error as:
dotnet.exe : System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Company' in the database.
Company table is on the top of the tables relationship, it seems that because the table Company is already there and the EF can not update the new table structure. If I change DB name in the connection string, it will create new database with new table structure without any issues. I am not sure how to address this issue? After the application go live in the near future I will properly make more changes to the Modes and will have same issue again and I cannot delete database with live data to recreate new table structure, Maybe I should configure it in the Startup.cs file, but I haven't found any useful resources yet. Please give me some advises.
I have attempted to change the DB Initializer as attached screenshot, but not sure how to do it.
I checked the project code again, the migration has not been applied to __MigrationHistory table, the migration code actually contained the code to create whole database structure as sample below:
migrationBuilder.CreateTable(
name: "Company",
columns: table => new
{
CompanyId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CompanyName = table.Column<string>(maxLength: 100, nullable: false),
IsAdmin = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Company", x => x.CompanyId);
});
And I haven't changed the project namespace. Recently I just made some changes on few table relationships such as site user permission table(company has many sites). I added a permission table, so now site user permission table can have multiple permissions type instead of single permission type.
Not sure how to set up automatic migrations in Entity framework core.

In Entity framework code first approch, there are four different database initialization strategies:
CreateDatabaseIfNotExists: This is default initializer. As the name
suggests, it will create the database if none exists as per the
configuration. However, if you change the model class and then run
the application with this initializer, then it will throw an
exception.
DropCreateDatabaseIfModelChanges: This initializer drops an existing database and creates a new database, if your model classes
(entity classes) have been changed. So you don't have to worry about
maintaining your database schema, when your model classes change.
DropCreateDatabaseAlways: As the name suggests, this initializer drops an existing database every time you run the application,
irrespective of whether your model classes have changed or not. This
will be useful, when you want fresh database, every time you run the
application, like while you are developing the application.
Custom DB Initializer: You can also create your own custom initializer, if any of the above doesn't satisfy your requirements or
you want to do some other process that initializes the database using
the above initializer.
So if you are using DropCreateDatabaseIfModelChanges or DropCreateDatabaseAlways then replace it with CreateDatabaseIfNotExists.
Please try this out.

Related

PostgreSQL error : the "PostAudienceEnum" type already exists

I generated a migrate.sql file from the prisma ORM which I then imported into my PostgreSQL database from Query Tool. However when I run this file I get the error: the "PostAudienceEnum" type already exists . I don't know why yet I did declare PostAudienceEnum as an enum . Here are the lines where we find the enumeration PostAudienceEnum:
-- CreateEnum
CREATE TYPE "PostAudienceEnum" AS ENUM ('PUBLIC', 'FRIENDS', 'ONLY_ME', 'SPECIFIC');
CREATE TABLE "Post" (
...
"audience" "PostAudienceEnum" NOT NULL DEFAULT E'PUBLIC',
...
CONSTRAINT "Post_pkey" PRIMARY KEY ("id")
);
This file was designed from my prisma schematic. I don't know how to modify it without messing up my database and why PostgreSQL throws this error.
You might be getting this error if the database already has data, and you're attempting to manually execute the SQL file against the database. You should only use prisma migrate to manage changes in your schema against your database. Prisma internally records what migrations have and have not been executed against the database, and attempting to run an SQL file manually outside of prisma migrate defeats the purpose of using it in the first place.
Migrate docs: https://www.prisma.io/docs/concepts/components/prisma-migrate
You should ONLY use Prisma Migrate to make changes to your database tables/columns/relationships, and not an external tool. However, if you are developing your database FIRST and then looking to keep your Prisma schema up to date with your database (and not the other way around), you will want to introspect your database. Same deal applies: Prisma knows what parts of your database are reflected in your Prisma schema and what's not.
Introspection docs: https://www.prisma.io/docs/concepts/components/introspection

Flywaydb error in kotlin

I want to use flywaydb in Kotlin but I have an error in use
My database is PostgreSQL and my ORM is Kotlin Exposed
Code:
val url = "jdbc:postgresql://127.0.0.1/test1"
Database.connect(url, driver = "org.postgresql.Driver", user = "postgres", password = "123")
var flyway = Flyway()
flyway.setDataSource(url, "postgres", "123")
flyway.migrate()
Error:
Exception in thread "main" org.flywaydb.core.api.FlywayException:
Found non-empty schema(s) "public" without schema history table! Use
baseline() or set baselineOnMigrate to true to initialize the schema
history table. at
org.flywaydb.core.Flyway$1.execute(Flyway.java:1197) at
org.flywaydb.core.Flyway$1.execute(Flyway.java:1168) at
org.flywaydb.core.Flyway.execute(Flyway.java:1655) at
org.flywaydb.core.Flyway.migrate(Flyway.java:1168)
How can I solve it? Where is my code wrong?
Found non-empty schema(s) "public" without schema history table! Use baseline() or set baselineOnMigrate to true to initialize the schema history table.
That error message pretty much says it all. You seem to be running Flyway on a database already populated with tables.
By default, Flyway expects to be run on a brand-new database, in a greenfield project. Flyway installs its own table first, for its internal tracking. This is the “schema history table” mentioned in your error message. After installing its own table, Flyway runs your SQL scripts creating further tables.
If adding Flyway to an existing database, choose either solution:
Recreate your database from scratch, starting with an empty database, running Flyway first, then writing and executing SQL scripts to recreate all the elements of your old database, and finally importing existing data.
Read about Flyway baseline feature, just as the error message suggested.

Restrict SqlEntityConnection Type Provider to only certain tables

I am writing a utility for myself that needs to be able to access a pair of tables in a SQL database. I used the SqlEntityConnection Type Provider and was rewarded with the data I needed from the table as easy to use entities.
One thing I noticed though was that startup and compiling of the project increased by quite a lot. I suspect this is because the database has over a hundred tables and it's compiling and getting data from all of them as opposed to just the two I need. Is there a way to restrict the EntityTypeProvider to only referencing the needed tables in the schema?
type private EntityConnection = SqlEntityConnection<ConnectionString="Server=Server;Initial Catalog=Database;Integrated Security=SSPI;MultipleActiveResultSets=true", Pluralize = true>
let private context = EntityConnection.GetDataContext()
I have not tried this myself, but I think you could add a new "ADO.NET Entity Data Model" (edmx) file to your project, let it generate from your existing database, and then delete from the model every table you don't want accessible to your code.
The EDMX designer will generate a *.csdl file that you can then reference from the LocalSchemaFile parameter of SqlEntityConnection. You'd use this parameter instead of ConnectionString.
The end result is that the entity provider would not automatically pick up changes to your database, but compilation times will go down, and only the tables you care about would be visible to your code.

NHibernate (and Fluent): Possible to prevent a specific table from being created via SchemaExport.Create?

I'm using Fluent NHibernate (and I'm a newbie). I have mapped a read-only table that already exists in the database (it's actually a view in the db). In addition, I have mapped new classes for which I want to create tables using SchemaExport.Create().
In my fluent mapping, I have specified "ReadOnly()" to mark the view as immutable. However, when I execute SchemaExport.Create(), it still tries to create the table so I get the error "There is already an object named 'vw_Existing'".
Is there a way to prevent NHibernate from trying to create that specific table?
I supposed I could export and modify the sql (SetOutputFile), but it would be nice to use SchemaExport.Create().
Thanks.
You're looking for
SchemaAction.None();

Doctrine schema changes while keeping data?

We're developing a Doctrine backed website using YAML to define our schema. Our schema changes regularly (including fk relations) so we need to do a lot of:
Doctrine::generateModelsFromYaml(APPPATH . 'models/yaml', APPPATH . 'models', array('generateTableClasses' => true));
Doctrine::dropDatabases();
Doctrine::createDatabases();
Doctrine::createTablesFromModels();
We would like to keep existing data and store it back in the re-created database. So I copy the data into a temporary database before the main db is dropped.
How do I get the data from the "old-scheme DB copy" to the "new-scheme DB"? (the new scheme only contains NEW columns, NO COLUMNS ARE REMOVED)
NOTE:
This obviously doesn't work because the column count doesn't match.
SELECT * FROM copy.Table INTO newscheme.Table
This obviously does work, however this is consuming too much time to write for every table:
SELECT old.col, old.col2, old.col3,'somenewdefaultvalue' FROM copy.Table as old INTO newscheme.Table
Have you looked into Migrations? They allow you to alter your database schema in programmatical way. WIthout losing data (unless you remove colums, of course)
How about writing a script (using the Doctrine classes for example) which parses the yaml schema files (both the previous version and the "next" version) and generates the sql scripts to run? It would be a one-time job and not require that much work. The benefit of generating manual migration scripts is that you can easily store them in the version control system and replay version steps later on. If that's not something you need, you can just gather up changes in the code and do it directly through the database driver.
Of course, the more fancy your schema changes becomes, the harder the maintenance will get i.e. column name changes, null to not null etc.