Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create database with Code-First

I am using Visual Studio 2015, Entity Framework v6, and SQL Server 2016 Express. In the past I created a database using a SqlConnection and SqlCommand and stuff the SQL into a string.

Now, I am teaching myself EF6 on Entity Framework Tutorial. On the simple code-first example (very simple), I literally copy and paste my code but still do not see the database created in SSMS. Neither does my code throw me any error.

Instead of pasting the code, I did a screenshot. I hope someone can point out what I am or the tutorial is missing.

enter image description here

[EDIT] Following Sampath's suggestion, I end up getting the following error: enter image description here enter image description here

[EDIT - Solved, sort of]

I apply the same code to another machine of same setup and the code works. So I suspect there are some corruption in the SQL Server or perhaps some registry is incorrect. I uninstall EVERY SQL Server version and related tools, delete all folders and files manually, then freshly reinstall SQL Server Express 2016 and tools. Then my code works.

I don't see this as a solution, but if someone can suggest what may have cause this problem I will try to recreate it or post a real solution to it.

like image 781
KMC Avatar asked Feb 13 '26 15:02

KMC


2 Answers

You have to give the connection string name on the web.config file as shown below.

Context :

public SchoolContext(): base("MySchoolDB")
        {

        }

App.config file

<add name="MySchoolDB" connectionString="Server=localhost; 
Database=YourDBName;Trusted_Connection=True;" providerName="System.Data.SqlClient" />

You can get more details here : Database Initialization

like image 153
Sampath Avatar answered Feb 16 '26 06:02

Sampath


You have to add entity to your database after configuring connection string, then DBContext will create database. Here is a connection string example:

<add name="Name" connectionString="Data Source=.; Initial Catalog=yourdbName; Integrated Security=True; MultipleActiveResultSets=True;"
      providerName="System.Data.SqlClient" />
like image 38
Omid Avatar answered Feb 16 '26 04:02

Omid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!