Create Identity (Membership) database with a different db-schema - sql-server

In my asp net core 3.1-project, Im trying out MS Identity, by adding Authentication when I create a new template (Asp net core 3.1+react)
I was hoping to add my Identity tables to a different schema, using this simple Guide,
ie
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema("notdbo");
}
But when I run "Update database" in package manager, it still creates a database in dbo-schema

Here is some reasons can cause this:
The user on on connection string should have access to the schema
If you have pending changes on model, this can cause issue. As initial migrations was based on the dbo schema and now you are trying to change the schema when having pending changes. Try to:
Option1:
Add-Migration (as mentioned in the comment) - This creates a new migration class as per specified name with the Up() and Down() methods.
Update-Database
Option2:
Remove the pending changes to the model
Run update-database. This will Executes the last migration file created by the Add-Migration command and applies changes to the database schema.
Change the schema, and you should be able to recreating the database

You need to add a valid migration first, before you do the Update-Database. The catch is that there is already one migration pending in the code, so that's why your change will not be detected.

Related

Recreate database when running ASP.NET Core Web API on another server

I have a project that is an ASP.NET Core Web API using Entity Framework Core.
A few time ago I created the database using code-first approach with the necessary migrations.
Now I want run the project in other machine and I get the error when I try for example an post to one endpoint:
Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open database "MyDatabase" requested by the login. The login failed.
However I think the problem (and I checked with ssms) is that the database doesn't exist.
My connection string, in DbContext is:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
}
What is the best way to recreate the database on this machine?
Thanks
Remove
;Database=MyDatabase
From the connection string.
Then you can create the dtaabase
CREATE DaTABASE MyDatabase
After the command has run
USE MyDatabase
so that you can create tables and run sql commands on it.
This will wrk on any database.
You should check prior to the creation if the database exists, bu that is highly depending on the rdms that you are using

I can't update the database using Entity Framework Core

I have an ASP.NET Core application that use SQL Server and EF Core. It contains two tables. I successfully created an Entity Framework Core migration and updated the database with it for the first table called Pies.
Then after I added another table called Feedbacks, I created a second migration.
However, when I attempt to update the database, it fails and I get this error:
Error Number:2714,State:6,Class:16
There is already an object named 'Pies' in the database.
Here is the DbContext class:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Pie> Pies { get; set; }
public DbSet<Feedback> Feedbacks { get; set; }
}
Since you have messed up the record history of EF Core migrations by deleting a migration file and your snapshot is tainted as well because you re-ran the migrations after deleting one.
Here are the steps you should take:
Delete all remaining migrations
Delete the database
Create a new initial migration
Create a new database.
In the future to avoid these error's use a version control system like git. And before creating any migrations commit. Note you will need to remove the incorrectly applied migration to your database from the _EfMigrations table in your database, since git doesn't version control your database.
This error occurs when there is a difference between the data in the database table and the files in the database.
You most likely created the database once and then deleted the migraine folder

EF 6.1 code first will not detect column changes

I am working on a web api project using EF 6.1.3 (code first) fluent API and SQL Server 2008 R2. I create migrations in code using add-migration and I have been able to create several migrations with no issues. Now I made a change to the model (increased column size for three columns in different tables) as follows:
Protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
... //previously these columns had length = 50
modelBuilder.Entity<EvalDef>().Property(t =>t.Name).HasMaxLength(70);
modelBuilder.Entity<ProgDef>().Property(t => t.Name).HasMaxLength(70);
modelBuilder.Entity<ReqDocDef>().Property(t => t.Name).HasMaxLength(70);
...
}
I am using the MigrateDatabaseToLatestVersion initialization:
protected void Application_Start()
{
Database.SetInitializer(new
MigrateDatabaseToLatestVersion<FtoContext,FTO.Model.Migrations.FtoConfiguration>());
}
Now when I run the add-migration command (from PM console), EF will not detect the changes to the model and an empty migration is created. I can't figure out why the fluent api model changes are not noticed when creating the migration.
Also, when I run the app, the OnModelCreating method is executed but I do not get any exception...which I would expect since now the DB schema would not match the current model.

Foreign Key constraint error when performing fresh install of Piranha CMS

Piranha CMS is a programmer oriented CMS (I prefer to write it since I've been downvoted last time!). I've spent all the afternoon trying to fix this problem : Whether I try to migrate from a Sql Compact Server Database to a SQL Server Database, or to start everything from scratch with an empty SQL Server Database, I get the following error :
Introducing FOREIGN KEY constraint 'FK_dbo.category_dbo.sysuser_category_updated_by' on table 'category' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I am able to pass the first step (admin account and password creation), but this exception is thrown whenever I try to log in.
What am I doing wrong ?
Thanks for your help !
UPDATE
The stack indicates where the error is coming from :
[HttpException (0x80004005): The pre-application start initialization method
Start on type Piranha.Web.ApplicationModule threw an exception with the following
error message: Introducing FOREIGN KEY constraint
'FK_dbo.category_dbo.sysuser_category_updated_by' on table 'category'
may cause cycles or multiple cascade paths. Specify ON
DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9915300
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr,
HttpContext context) +254
There seem to be a problem with the Method Start of Piranha.Web.ApplicationModule.
Also I have noticed the configuration of Entity Framework is :
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
I wonder about the :
invariantName="System.Data.SqlClient
Since System.Data.SqlClient is the Provider mentionned in my connection string. But I don't know if it's relevant since it may just mean that EF is used to retrieve the data. But I wonder if there might not be a conflict since both your internal scripts and EF use this connection string with this provider that is mentionned. Also, I'm not sure, but I know that with code-first EF also creates meta-data when it creates a database. Perhaps since your internal scripts doesn't create them, EF considers that the DB doesn't exist ?
Update 2
I have some news, I have added
Database.SetInitializer<Piranha.DataContext>(null);
In Application_Start to avoid Database recreation. It seems to have solved the database re-creation problem. I no longer see the exception concerning the constraint. However now the PageController throws a null reference exception after trying to log in, and I still can't see anypage of the public website (The publc site throws an internal server error). My guess is that when I set the Initializer to null, it also prevents EF from populating the DB with the basic data of the Framework. That's a good step further, so it seems that the problem comes from the Piranha DataContext Configuration.
Update 3
Just to give more details :
When trying to log in, I'm redirected to manager/page which throws a null reference exception as I said before. This exception is thrown when I try to access most of the pages of the manager (I have tried template/pagelist, setting/userlist) however, when I try "manager/post" I get the following error :
Invalid object name 'dbo.post'.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.post'.
But the 'post' Table do exist in the Database... It's a fresh install, I only changed two things : the connection string, and the Database Initializer code I added in Global Asax.
As far as i can see, in version 2.2.0 there is not a constraint for table "category" with the name "FK_dbo.category_dbo.sysuser_category_updated_by". I guess something went wrong installing a fresh version.
If you have access to SQL server with a management tool (like 'SQLServer Management Studio'), try to run to following query against your Piranha-database:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='category' AND CONSTRAINT_TYPE='FOREIGN KEY'
You should see three constraints, none of them with the word 'sysuser' in its name.
You might want to try a fresh install again, following the instructions here:
http://piranhacms.org/docs/introduction/getting-started
Before you proceed with the web installer, you should create a clean empty database using SQL Server Management Studio. You can run these SQL-commands in the Management Studio:
-- create new user
CREATE LOGIN piranha2 WITH PASSWORD = 'piranha2'
GO
-- create new empty database
CREATE DATABASE piranha2
GO
-- select new database
USE piranha2
GO
-- assign user to database
CREATE USER piranha2 FOR LOGIN piranha2
GO
-- add role to user
EXEC sp_addrolemember 'db_owner', 'piranha2'
GO
After that, open Web.config, look for section "connectionStrings". You should see a couple of lines. Add a new line in this section with this content (don't forget to use your own servername or ip-address after "server="):
<add name="piranha" connectionString="server=192.168.1.1;database=piranha2;user id=piranha2;password=piranha2;multipleactiveresultsets=true;" providerName="System.Data.SqlClient" />
Start the installer. It should find your database and create tables and constraints.
Hope that will help.
The error message you're providing is a typical Entity Framework error when trying to create a DbContext in the database. The only problem is that Entity Framework is not responsible for creating the tables in Piranha CMS, this is done by internal SqlScripts embedded in the framework dll.
If the tables are created successfully in the database and you still get this error when trying to log in, my only guess is that Entity Framework is for some reason using an incorrect Connection String trying to create the database somewhere else. Although I'm puzzled how this could happen through misconfiguration.
Can you access the public site after install?
UPDATE
I've created a new Blank MVC Application, installed PiranhaCMSMvc into it, installed the database and logged into the manager without problems. I've pushed the blank project to this repo:
https://github.com/tidyui/Blank
Download this source code and see if it works for you after you've modified the connection string. If it works, try to compare the projects to see what is causing your error. If it doesn't work then there's something else wrong with your setup that is conflicting somehow. Keep me updated!
Regards
Reason for error is Schema name in my case.
Solution:
You require to have database objects belonging to dbo schema, if you've installed on fresh database with different schema name, it will throw this error. To fix it, change schema name of those tables to dbo and it will work like a charm.
Well, I spent 2 days on it so I had no choice but to change CMS. I'm running late because of this problem. Fortunately I only had created a couple of pages. I'm currently moving to Umbraco. I've played with it this afternoon and it's actually less complicated than what I heard so it should do the trick. It's also perfectly working on my production server.
However, I still have an other project that I would like to keep on Piranha CMS. Since I've planned to move it from Compact SQL to SQL Server too, I'm really concerned with this issue.
I cannot add a comment yet, so have to give a second answer:
My previous answer didn't make sense so i have to make something up with you.
If you still want to investigate some time:
to re-produce your problem i've created a VHD with Windows 7 Pro-N (un-activated), MS SQL 2012 Express and VS 2013 Express Web. You can run this as virtual machine either under Windows 7 Virtual PC or Windows 8 Hyper-V. With the Blank project of Hakan I was not able to reproduce your problem. However, if you manage to re-produce your problem in this virtual machine, you can share the VHD with Hakan so he can take a look what is happening (of course if he's willing to do so).
Also, what i'm wondering: if you rename the affected table or drop it, is the error-message moving to another table and/or constraint? Of course it is not a solution to drop the table, but it might tell more about what is going on.

Setting up a Entity Framework Code First Database on SQL Server 2008

I successfully created my first Entity Framework Code first project using SQL Server CE. The database tables were created automatically and all was well.
I then changed my connection string to point to a SQL Server database I'd created and expected it to autogenerate the tables. It didn't and instead complained about the tables not existing.
After some reading I found that I needed to add an initializer to my App_Start method.
I tried:
// Method 1
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFContext>());
But this didn't work at first because it couldn't find an EdmMetaData table to discover if the model had changed.
So I tried adding:
// Method 2
Database.SetInitializer(new CreateDatabaseIfNotExists<EFContext>());
But this didn't work because I'd already created the database, and when I removed the database it still didn't work because the user I was logging in as didn't have create database privileges.
I finally tried:
// Method 3
Database.SetInitializer(new DropCreateDatabaseAlways<EFContext>());
Which worked, but I don't really want to drop the db every time. So once it ran and added the EdmMetaData table I replaced it with method 1 and that now works fine.
Although this method works, it doesn't feel as elegant as when I was using SQL Server CE and I've not found someone suggesting that you use this method.
So, am I missing something and is there an easier, more elegant way to do this?
Method 1 and 2 expects that database doesn't exist yet. They don't work if you create database manually. If you need EF to create tables in existing database you must create custom database initializer.

Resources