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

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.

Related

Schema error when running update-database command to create identity tables for npgsql data provider

I am manually creating the identity tables for a new ASP.NET 6 project following this tutorial. Such tutorial is for MS SQL Server and I am using PostgreSQL so I made the appropriate modifications. Although the process is straightforward, I have a problem when reaching the update-database step where I get the following error: "Couldn´t set schema (Parameter ´schema')". My connection string is as follows: "host=localhost; database=testdb001; schema=testdb001; port=5433; user id=some-user; password=some-password;". I found that such error disappears and the identity tables are successfully created if I remove the schema parameter in the connection string but tables are created in the public schema that PostgreSQL automatically includes when a new DB is created. However, I do not want this to happen because I want to use another schema name. I visited connection strings website for PostgreSQL (https://www.connectionstrings.com/postgresql/) and I see a link for Npgsql, and all the examples here do not contain the schema parameter. This is the first time that I use npgsql. Is there a way to create the identity tables in a specific schema name?
Maybe a workaround is to specify a schema name in the search_path parameter in postgresql.conf file but this would lead to add a name every time I define a new schema. I think that the schema name in the connection string is a great choice but I wonder why this is not accepted for npgsql.
Respectfully,
Jorge Maldonado
I found the solution.
For npgsql you must use search path as a connection string parameter instead of schema. So a connection string is as follows
"host=localhost; database=testdb001; search path=testdb001; port=5433; user id=some-user; password=some-password;"
and not
"host=localhost; database=testdb001; schema=testdb001; port=5433; user id=some-user; password=some-password;"
Regards,
Jorge Maldonado

Entity Framework Data First - Invalid Object Name dbo.TableName

sup?
I got this problem wich has been slowing down my production a lot, hope u guys can give me any tip on how to solve it....
I'm currently using EF6 and a custom ConnectionString with a connectionString builder class that reads and external xml file.
My database is all set up and running in SQL 2010 and Management Studio ok, but whenever I generate the edmx file, it generates the class mappings okay, I've compared the original ConnectionString to my ConnectionString Builder they're the same, changed the :base to receive a custom ConnectionString, all set.
But when I try to save changes it doesn't find the table object, I have deleted it, created again from the start, still same "Invalid database object Dbo.TableName" error.
Does any one have a clue on this?
Thanks in Advance!
This error is not coming from Entity Framework but directly from the database.
Use SQL Profiler and include in the trace the "DatabaseName" and "ServerName" and you will find out it's not the same as your expected.
The only other options which this issue happen is if your "tableName" is not the same as the table name in SQL, so run the SQL from the SQL Profiler directly into SSMS.

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.

creating view in sqlserver

I trying to create view linking 2 tables admins and news
create view v_news as
SELECT [n_id]
,[n_title]
,[n_detail]
,[n_date]
,[n_sdate]
,[n_edate]
,[n_admin]
,[a_name]
,[a_email]
,[a_role]
,[a_status]
FROM hed2.dbo.hed_news,hed2.dbo.hed_admins
where hed_admins.a_id=hed_news.n_admin
This message is displayed:
Command(s) completed successfully.
but there is no view in VIEWS folder.
When I try to run the same query again then it says:
There is already an object named 'v_news' in the database.
I am connected with windows authentication
I tried reconnect and restart sql server but ....
Your view is using ANSI 92 syntax. While this will work for older database versions, it will not work in SQL Server 2012. See Mike Walsh's blog on this topic.
1 - When using SSMS views do not show up right away. Right click and hit refresh.
2 - It is very important to make sure you are in the correct database. I am sure many people, including me, have create an object or two in master. This is the default for a new login.
This can be changed by changing the default database for your login.
3 - Execute the USE command to change the database context (default).
The snippet below is a SQL Server 2012 compliant version.
USE [hed2]
GO
create view v_news as
SELECT [n_id]
,[n_title]
,[n_detail]
,[n_date]
,[n_sdate]
,[n_edate]
,[n_admin]
,[a_name]
,[a_email]
,[a_role]
,[a_status]
FROM dbo.hed_news JOIN dbo.hed_admins ON hed_news.n_admin = hed_admins.a_id
GO
Three things:
You must use JOINS and the way your query is written is bad. Just an observation. Nothing to do with your question.
Did you try running SELECT * FROM v_news? That would return results.
Right click and views in SSMS and select refresh. It will show up in the list
Raj

How to connect opencart with mssql server

Is there any chance of connecting opencart with mssql? Have anyone tried? If so what is the procedure of doing that?
That should not be a big problem, You only need to do:
create /system/database/mssql.php class - the class should have the same methods, properties and functionality as e.g. the mysql.php one
rewrite all of the model classes method's queries to meet the MS SQL / T-SQL SQL syntax
in both config files (/config.php and /admin/config.php) set the proper DB_DRIVER - mssql
I am supposing You have the OpenCart database created already due to the /install/opencart.sql file.
I guess nothing more should be done.
Anyway, what is the reason for switching to MS SQL?
EDIT: In /system/database/ there is this mmsql.php file which actually contains the MSSQL class thus this do not have to be implemented, just renamed to mssql.php file.

Resources