Cannot create database with Code-First - c#

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.
[EDIT]
Following Sampath's suggestion, I end up getting the following error:
[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.

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

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" />

Related

Entity Developer/EntityFramework - The specified named connection is either not found in the configuration

Using Devart Entity Developer with Entity Framework 6. I have my main class library project. I had a different Winform project altogether that uses Entity Developer/Entity Framework that I developed to do some database work with Sql. I decided to add this secondary Winform project to the main class library.
First I tried adding the Winform project to the solution. That did not work well. Even though I added a reference to the exe of the Winform project it seems not to find it ok. I removed that project from the solution.
As a second attempt. I copied the classes from the Winform project (two of them) to the main class library project and recreated the Entity Developer/Entity Framework stuff. Now when I run the project everything runs (including the new form) but I cannot connect to the database. I get the error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
The line that has the error is the line calling base:
public SWPDMEngVaultEntities() :
base(#"name=SWPDMEngVaultEntitiesConnectionString", "SWPDMEngVaultEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
My connection string is in the app.config file and looks like this:
<connectionStrings>
<add name="SWPDMEngVaultEntitiesConnectionString" connectionString="metadata=res://*/DataModel1.csdl|res://*/DataModel1.ssdl|res://*/DataModel1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=XXXXXX\SQLEXPRESS;Initial Catalog=XXXXXX;Integrated Security=False;Persist Security Info=True;User ID=XXXXXX;Password=XXXXXX""
providerName="System.Data.EntityClient" />
</connectionStrings>
All of the XXXXXX's in the above string have been confirmed as correct. Also, Entity Developer has a "Test Connection" and the test connection connects just fine. Entity Developer also gets the database information OK so I know it is able to connect without issue. The problem is at runtime on the solution.
I have looked at other posts about this error and they all seem to be saying make sure your connection string is good. What else should I check?
The answer to this issue came from Devart. Class libraries do not use app.config files for settings. By default the connection string in the Devary generated templates are stored in the app.config file. There is a place to turn this off when the model is generated.

local DB error 50 [duplicate]

I am trying to build an ASP.NET MVC 5 Web Application which has a MyDatabase.mdf file in the App_Data folder. I have SQL Server 2014 Express installed with a LocalDb instance. I can edit the database tables using the Server Explorer, however when I debug the application and go to a page where the database is needed I get the following error.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
So I looked in the Event Viewer under Application and only see one Warning over and over again.
The directory specified for caching compressed content C:\Users\User1\AppData\Local\Temp\iisexpress\IIS Temporary Compressed Files\Clr4IntegratedAppPool is invalid. Static compression is being disabled.
So I tried rebooting the server, still no go. Same error 50 as before.
I have created an class under Models where I have a class called Post.
namespace MyApplication.Models
{
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
public class MyDatabase : DbContext
{
public DbSet<Post> Posts { get; set; }
}
}
I also have a Controller setup to list the posts from MyDatabase.
namespace MyApplication.Controllers
{
public class PostsController : Controller
{
private MyDatabase db = new MyDatabase();
// GET: Posts
public ActionResult Index()
{
return View(db.Posts.ToList());
}
}
In my web.config file the connection string looks like this...
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDB)\v12.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I've tried the suggestion posted here but it didn't work. Also tried this.
I also notice that the MyDatabase instance gets disconnected after I start running the application. If I refresh the database using Server Explorer in Visual Studio I can view the tables.
How is it that I can connect to the database and edit it within Visual Studio 2013 but when I debug the application it cannot connect to the database?
Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb as server name to connect to the LocalDB automatic instance, for example:
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb;
...
The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.
Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb value instead of v12.0 and see if that corrects your issue.
Running this:
sqllocaldb create "v12.0"
From cmd prompt solved this for me...
I usually fix this errore following this msdn blog post Using LocalDB with Full IIS
This requires editing applicationHost.config file which is usually located in C:\Windows\System32\inetsrv\config. Following the instructions from KB 2547655 we should enable both flags for Application Pool ASP.NET v4.0, like this:
<add name="ASP.NET v4.0" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated">
<processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>
To begin - there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)\mssqllocaldb
Possible Issues
You don't have the services running
You don't have the firelwall ports here
configured
Your install has and issue/corrupt (the steps below help give you a nice clean start)
You did not rename the V11 or 12 to mssqllocaldb
\\ rename the conn string from v12.0 to MSSQLLocalDB -like so->
`<connectionStrings>
<add name="ProductsContext" connectionString="Data Source= (localdb)\mssqllocaldb;
...`
I found that the simplest is to do the below - I have attached the pics and steps for help.
First verify which instance you have installed, you can do this by checking the registry& by running cmd
1. `cmd> Sqllocaldb.exe i`
2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"`
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"`
4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`
ADVANCED Trouble Shooting Registry configurations
Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry
Paths
// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\(instance-name)
// OLD SQL SERVER
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLServer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
// SQL SERVER 6.0 and above.
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLExecutive
// SQL SERVER 7.0 and above
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLServerAgent
HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server 7
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServ65
Searching
SELECT registry_key, value_name, value_data
FROM sys.dm_server_registry
WHERE registry_key LIKE N'%SQLAgent%';
or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'DECLARE #returnValue NVARCHAR(100)'
SELECT #SQL = #SQL + CHAR(13) + 'EXEC master.dbo.xp_regread
#rootkey = N''HKEY_LOCAL_MACHINE'',
#key = N''SOFTWARE\Microsoft\Microsoft SQL Server\' + RegPath + '\MSSQLServer'',
#value_name = N''DefaultData'',
#value = #returnValue OUTPUT;
UPDATE #tempInstanceNames SET DefaultDataPath = #returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames
-- now, with these results, you can search the reg for the values inside reg
EXEC (#SQL)
SELECT InstanceName, RegPath, DefaultDataPath
FROM #tempInstanceNames
Trouble Shooting Network configurations
SELECT registry_key, value_name, value_data
FROM sys.dm_server_registry
WHERE registry_key LIKE N'%SuperSocketNetLib%';
An instance might be corrupted or not updated properly.
Try these Commands:
C:\>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
C:\>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
C:\>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
C:\>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.
maybe this error came because this version of Sql Server is not installed
connectionString="Data Source=(LocalDB)\v12.0;....
and you don't have to install it
the fastest fix is to change it to any installed version you have
in my case I change it from v12.0 to MSSQLLocalDB
Final Solution for this problem is below :
First make changes in applicationHost config file. replace below string setProfileEnvironment="false" TO setProfileEnvironment="true"
In your database connection string add below attribute : Integrated Security = SSPI
I ran into the same problem. My fix was changing
<parameter value="v12.0" />
to
<parameter value="mssqllocaldb" />
into the "app.config" file.
All PLEASE note what Tyler said
Note that if you want to edit this file make sure you use a 64 bit text editor like notepad. If you use a 32 bit one like Notepad++ it will automatically edit a different copy of the file in SysWOW64 instead. Hours of my life I won't get back
In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations.
Make sure to select the proper start project.
I have solved above problem Applying below steps
And after you made thses changes, do following changes in your web.config
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v12.0;AttachDbFilename=|DataDirectory|\aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />
My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:\Program Files\Microsoft SQL Server where i found
3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

Error when connecting to local SQL Server database [duplicate]

I am trying to build an ASP.NET MVC 5 Web Application which has a MyDatabase.mdf file in the App_Data folder. I have SQL Server 2014 Express installed with a LocalDb instance. I can edit the database tables using the Server Explorer, however when I debug the application and go to a page where the database is needed I get the following error.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
So I looked in the Event Viewer under Application and only see one Warning over and over again.
The directory specified for caching compressed content C:\Users\User1\AppData\Local\Temp\iisexpress\IIS Temporary Compressed Files\Clr4IntegratedAppPool is invalid. Static compression is being disabled.
So I tried rebooting the server, still no go. Same error 50 as before.
I have created an class under Models where I have a class called Post.
namespace MyApplication.Models
{
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
public class MyDatabase : DbContext
{
public DbSet<Post> Posts { get; set; }
}
}
I also have a Controller setup to list the posts from MyDatabase.
namespace MyApplication.Controllers
{
public class PostsController : Controller
{
private MyDatabase db = new MyDatabase();
// GET: Posts
public ActionResult Index()
{
return View(db.Posts.ToList());
}
}
In my web.config file the connection string looks like this...
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDB)\v12.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I've tried the suggestion posted here but it didn't work. Also tried this.
I also notice that the MyDatabase instance gets disconnected after I start running the application. If I refresh the database using Server Explorer in Visual Studio I can view the tables.
How is it that I can connect to the database and edit it within Visual Studio 2013 but when I debug the application it cannot connect to the database?
Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb as server name to connect to the LocalDB automatic instance, for example:
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb;
...
The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.
Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb value instead of v12.0 and see if that corrects your issue.
Running this:
sqllocaldb create "v12.0"
From cmd prompt solved this for me...
I usually fix this errore following this msdn blog post Using LocalDB with Full IIS
This requires editing applicationHost.config file which is usually located in C:\Windows\System32\inetsrv\config. Following the instructions from KB 2547655 we should enable both flags for Application Pool ASP.NET v4.0, like this:
<add name="ASP.NET v4.0" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated">
<processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>
To begin - there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)\mssqllocaldb
Possible Issues
You don't have the services running
You don't have the firelwall ports here
configured
Your install has and issue/corrupt (the steps below help give you a nice clean start)
You did not rename the V11 or 12 to mssqllocaldb
\\ rename the conn string from v12.0 to MSSQLLocalDB -like so->
`<connectionStrings>
<add name="ProductsContext" connectionString="Data Source= (localdb)\mssqllocaldb;
...`
I found that the simplest is to do the below - I have attached the pics and steps for help.
First verify which instance you have installed, you can do this by checking the registry& by running cmd
1. `cmd> Sqllocaldb.exe i`
2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"`
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"`
4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`
ADVANCED Trouble Shooting Registry configurations
Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry
Paths
// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\(instance-name)
// OLD SQL SERVER
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLServer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
// SQL SERVER 6.0 and above.
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLExecutive
// SQL SERVER 7.0 and above
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLServerAgent
HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server 7
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServ65
Searching
SELECT registry_key, value_name, value_data
FROM sys.dm_server_registry
WHERE registry_key LIKE N'%SQLAgent%';
or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'DECLARE #returnValue NVARCHAR(100)'
SELECT #SQL = #SQL + CHAR(13) + 'EXEC master.dbo.xp_regread
#rootkey = N''HKEY_LOCAL_MACHINE'',
#key = N''SOFTWARE\Microsoft\Microsoft SQL Server\' + RegPath + '\MSSQLServer'',
#value_name = N''DefaultData'',
#value = #returnValue OUTPUT;
UPDATE #tempInstanceNames SET DefaultDataPath = #returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames
-- now, with these results, you can search the reg for the values inside reg
EXEC (#SQL)
SELECT InstanceName, RegPath, DefaultDataPath
FROM #tempInstanceNames
Trouble Shooting Network configurations
SELECT registry_key, value_name, value_data
FROM sys.dm_server_registry
WHERE registry_key LIKE N'%SuperSocketNetLib%';
An instance might be corrupted or not updated properly.
Try these Commands:
C:\>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
C:\>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
C:\>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
C:\>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.
maybe this error came because this version of Sql Server is not installed
connectionString="Data Source=(LocalDB)\v12.0;....
and you don't have to install it
the fastest fix is to change it to any installed version you have
in my case I change it from v12.0 to MSSQLLocalDB
Final Solution for this problem is below :
First make changes in applicationHost config file. replace below string setProfileEnvironment="false" TO setProfileEnvironment="true"
In your database connection string add below attribute : Integrated Security = SSPI
I ran into the same problem. My fix was changing
<parameter value="v12.0" />
to
<parameter value="mssqllocaldb" />
into the "app.config" file.
All PLEASE note what Tyler said
Note that if you want to edit this file make sure you use a 64 bit text editor like notepad. If you use a 32 bit one like Notepad++ it will automatically edit a different copy of the file in SysWOW64 instead. Hours of my life I won't get back
In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations.
Make sure to select the proper start project.
I have solved above problem Applying below steps
And after you made thses changes, do following changes in your web.config
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v12.0;AttachDbFilename=|DataDirectory|\aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />
My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:\Program Files\Microsoft SQL Server where i found
3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

Cannot Open Database in Visual Studio

I'm going through the ASP.NET "Contoso University" Tutorial found here.
The problem starts when i try to view the database. Following directly from the tutorial, when i go to open the database (SchoolContext), i get this error mesage.
Cannot open database "ContosoUniversity1" requested by the login. The login failed.Login failed for user 'machine\user'.
So on the DB i went to "Modify Connection" and hit OK without changing anything. Then I was able to view the database, tables, views, etc. But there was no info available, so continuing from the tutorial I should have seen the Student entity, but it was not there. And when i run the program and try go to website/students, i get a 404 saying the resource cannot be found.
The connection string i'm using from the tutorial
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
I'm running VS 2013 Community Express. I do not have SQL Server Management Studio installed or any related programs.
I'm on the admin user for the computer.
Is this a problem with my machine or user rights? Do i need to install another program?
I think you are using the sqlserver express edition which comes with Visual Studio installation. Try adding AttachDBFilename='path of .mdf file of database' also in your connection string.
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\ContosoUniversity1.mdf" providerName="System.Data.SqlClient"/>
</connectionStrings>
Go to that connection in Server Explorer. Go to Properties and use the connection string from there.

What providerName and connectionStrings should be used for MS SQL Compact Edition in MVC 4 in Visual Studio 2013 in ASP.NET MVC 4?

What providerName should be used in Web.config file for MS SQL Compact Edition in MVC 4 in Visual Studio 2013?
Introduction
When I use:
<connectionStrings>
<add name="MusicStoreEntities"
connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
my website database works and Genre objects are retrieved from database and displayed
after I change of providerName to providerName="System.Data.SqlClient like this:
<connectionStrings>
<add name="MusicStoreEntities"
connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf"
providerName=providerName="System.Data.SqlClient"/>
</connectionStrings>
I get:
So WHY I want to change anything?
Actual problem:
If I leave providerName="System.Data.SqlServerCe.4.0" when I want to add new controller by this menu:
I get:
but if I set providerName="System.Data.SqlClient the StoreManagerController is generated but the database does not work at all.
Question: What should I do to generate StoreManagerController? I follow this tutorial: http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-5 and link to the working project just before that step it: http://www.speedyshare.com/RGdqH/MvcMusicStore.zip
So bare in mind the "Mvc Music Store" was MVC 101 since the beginning of MVC. Given there have been a lot of changes, the chances of the documentation/walk-throughts being a little off are unfavorable. With that said:
The T4 template for the data-driven controller is obviously failing due to your connection string. This is most likely because SQL Express (in it of itself) has gone through a lot of cycles and is now following LocalDB. Given you're using MVC4, it's probably a good time to upgrade, and this means you can have all the benefits of SQL Express (including the System.Data.SqlClient provider) without the possible headaches from previous revisions.
With that said, change your connection string to use the new format:
<connectionStrings>
<add name="MusicStoreEntities"
connectionString="Data Source=(localdb)\v11.0;Integrated Security=true;AttachDbFileName=|DataDirectory|MvcMusicStore.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
And (probably) re-run your DatabaseInitializer (if I recall correctly, this should happen automatically since it's using EF. If not, you can go to your Package Manager console and run Update-Database).
This now gives you the provider the Controller template wants while still keeping it as a local (dev) database.
Delete the database your local server(make sure u do a back up off data / your seed method has relevant data needed)
Delete all migration class files besides the configuration file from your Migrations Folder. (migrations need to be enabled in order for this to work "Enable migrations" )
In the Package Manage Console type the following command: “ add-migration update ”. Once that is successful
Type in “Update-Database” in the Package Manager Console.
Your Database will be recreated without ANY data.
I have the same problem for MVC5, so i change the web.comfig connection string for:
<add name="MusicStoreEntities" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|MvcMusicStore.mdf Catalog=MvcMusicStore" providerName="System.Data.SqlClient"/>
it works for me!

Categories