Creating a database project with Visual Studio - can't find database after running? - asp.net

I am following this tutorial (http://www.asp.net/mvc/overview/getting-started/database-first-development/setting-up-database) in order to create a database-first app with Entity Framework.
I hit "Run" and everything seems to be working, but in the next part of the tutorial (https://www.asp.net/mvc/overview/getting-started/database-first-development/creating-the-web-application), when I try to add a connection, it's not in the drop-down menu in the "Connection Properties" box under "Select or enter a database name".
Which server is the database on? I didn't specify anything about the server when I created the project for the first tutorial, and I figured that it would be on the default LocalDB that comes with Visual Studio (server name: (localdb)\MSSQLLocalDB), but the database isn't there. Any ideas where I should look or what to try?

Maybe use . (a dot) as Server Name?

Open your Web.config file and check your <connectionStrings> this is where the data source of the database will be. As shown:
However, which version of SQL Server do you have? As this can determine what the correct connection string will be.
Hit Windows+R. And run the following:
%LOCALAPPDATA%\Microsoft\Microsoft SQL Server Local DB\Instances
You may have multiple instances, it would be worth checking each one. So it would be:
(localdb)(name of instance)
This article may also be of use to you:
http://rajchel.pl/2015/10/solving-connection-issue-with-sql-server-2014-localdb/

What could be the case is that you have to run the application you created, and then do something to touch the database like creating / registering a user. After registration you can find the database on the specified location in your web.config settings. This was the solution in my case.

Related

I can't seem to create a SQL Server database with Visual Studio in data connections

I'm trying to create a SQL Server database and then to use it to make a list with important stuff in it. I don't seem to make it work. I went to the toolbox, chose panel and then when I get into creating the server itself, it doesn't work as it is not showing me a server name and the database name needed for it to work. I tried to write them myself but it's still not working.
Both of them when I open the list don't show anything. I understood that is essential for it to show me things for it to work.
You could install LocalDB through the Visual Studio Installer, as part of the Data Storage and Processing workload, the ASP.NET and web development workload, or as an individual component.
After you install it, you could get it directly.
Here is the full documentation about LocalDB.
You can also refer to this set of ssdt database operation process to learn database.

ASP.NET MVC4 Code First - 'Cannot attach the file as database' exception

I'm using Code First concept in Entity Framework and I'm constantly getting the following exception while starting application:
Cannot attach the file 'C:\Users\Admin\Documents\Visual Studio 2012\
Projects\Pro\Pro.Web\App_Data\Pro.mdf' as database 'Pro'.
I've put this in Global.asax.cs but also without success:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ProWebContext>());
var ctx = new ProWebContext();
ctx.Database.Initialize(true);
I've checked under App_Data directory and there no database created. Also, under Server Explorer there is nothing under Data Connections. Everything was working fine yesterday and today not working at all. I've tried to connect to LocalDB with SQL Server Management studio but it says it cannot connect to local database. Any ideas what could be a problem?
Thanks!
I found the solution. With newest SQL Server Management studio there is no problem in connecting to the local database. Connection needs to be established like this:
After logging in we can still see old database present even if there is nothing under App_Data directory and under Data Connections in Server Explorer in Visual Studio. When we delete that database from SQL Server Management studio and start application again there will be no more errors while attaching database.
I was facing the same error when I saw this but I couldn't delete the database using SQL Server Management Studio so I remembered IDatabaseInitializer.
Setting a database initializer for my Code First context solved the issue. In my case adding an initializer to always drop the DB worked (I added the code in the static constructor of my context, most people add it in Global.asax):
static SomeDbContext()
{
System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseAlways<SomeDbContext>());
}
There are other initializers of course.
I just got into the same problem, and yet the answers above helped, the solution was different.
In my case, I was reusing a project that has already created it´s database. And since the name in the config was the same, it was throwing the exception, missleading the real solution.
It worth checking the database is not created and is different than the ones you used before. Change the name and go ahead.
I deleted the mdf file manually so the code will recreate it again, and had the same problem. I solved it by running update-database command in the package manager console.

How to work with LocalDB and EF, without using migrations

I am on VS 2012 RTM, with EF 5. I am doing Code First, but trying to ignore Code Migrations since I am just in development. To avoid them, I have this set
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());
Occasionally, even when I don't think I've touched the model, it decides to recreate. That's fine. But it usually results in the error
Cannot drop database because it is currently in use.
So I decided to delete the database entirely. I go into VS, go to the "SQL Server Object Explorer", find the DB and delete it. Now I'm stuck at
Cannot attach the file '{0}' as database '{1}'
I had this happen last night and I just fiddled around until it work (shut down tasks, restart VS, changed the DB and file names in the web.config, etc.
So question 1) How do I get out of this state?
But the more important question, how do I prevent myself from getting in this state at all?
The SQL Server Object Explorer window can hold a connection to the database. Closing the window and all windows opened from it releases the connection.
I had the same problem and managed to fix it. The main problem is that EF won't automatically create the database. The solution is not very hard.
First, go to the Solution Explorer and manually create the database. To do this, go to the folder where your database is located (usually App_Data). Right-click on this folder and click on Add -> New Item. Select the Data tab and select SQL Server Database. Make sure you enter the name Entity Framework expects (which is specified in the Cannot attach the file '{0}' as database '{1}' error message).
Then most likely you will get an error message that says that the database does not contain any model metadata. To circumvent this, change your database initialisation to:
Database.SetInitializer(new DropCreateDatabaseAlways<SomeContext>());
Now run the application and the database should be there with tables correctly created. Once this step has been successfully executed, you change change your database initializer back to:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());

Problem connecting to database - user instance and Entity Framework issue

I've created an entity model file (.edmx) based on an .mdf file in my asp.net application, placed in my App_Data Folder.
first of all my connection string, created by the entity framework wizard :
<connectionStrings>
<add name="Sales_DBEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='data source=.\SQLEXPRESS;attachdbfilename="c:\users\ext\documents\visual studio 2010\Projects\WebProject_A\WebProject_A\App_Data\Sales_DB.mdf";integrated security=True;USER INSTANCE=TRUE;multipleactiveresultsets=True;App=EntityFramework'"
providerName="System.Data.EntityClient" />
</connectionStrings>
The above is placed in an app.config file created by the wizard.
I've copied the same connection string to the web.config file as well (I'm not sure if this is necessary).
I've come across two problems when attempting to later run the same application on a my machine (I've created the application on a different machine).
The first was regarding the user instance:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed
The first thing I don't really comprehend is what a user instance actually defines.
According to MSDN :
A user instance is a separate instance of the SQL Server Express Database Engine that is generated by a parent instance
Is my local database considered a user instance ?
I would really like some clarification on the matter because I came across posts suggesting
to mark it as False, and the reason was not clear to me .
another post on this matter
From there I came across another solution that explains that for this problem you need to
enable user instance in the SQL Server on your machine.
The Fix
I've done what was explained in that post
but now I've come across a new problem :
An attempt to attach an auto-named database for file (Full Path to my app_data\my.mdf file) A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I've already attempted to delete all the files under
C:\Documents and Settings\(your user account name)\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
and rebooting like suggested in other posts, but still I can't find a clear solution for this problem.
I know this is a long post but any help would be appreciated
thanks in advance.
Read this very good overview of what user instances really are.
In a nutshell:
SQL Server allows you to have multiple instances of itself on a single computer - the default instance can be accessed using just the machine name (or IP address) of the host machine - all other instances need to be specified by an instance name (like the SQLExpress on your machine)
for development purposes, you can also create a user instance - each user gets their own separate instance of SQL Server (works in the Express edition only) and a database is attached by its file name (path\Sales_DB.mdf) to that user instance. This instance is started up on demand, then runs and is shut down when no longer needed
While this works great for development, it's not really intended for later on - certainly not for production use.
In a production environment, you want to attach your database files to the actual SQL Server instance they should run on - typically using SQL Server Management Studio. When you do this, you no longer refer to that database via its file name, but instead you use the database name that was given to the database when being attached to the server. In this case, SQL Server will handle all details of operations - and that SQL Server instance is up and running all the time (doesn't need to be started "on demand" all the time), and you can use things like permissions and logins to control access to the database.
Your connection string would then look something like this:
<connectionStrings>
<add name="Sales_DBEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='server=YourServerNameHere;database=Sales_DB;integrated security=True;App=EntityFramework'"
providerName="System.Data.EntityClient" />
</connectionStrings>
When you have attached a database to a production (or testing) SQL Server instance, you do not need to know what the files are that make up the database, and you don't need to specify those files - SQL Server will take care of that. You just refer to the database via its database name.
The solution is always simpler then anticipated:
double click the model.edmx file -> the designer will open.
right click on the designer -> Update model from database .
new connection -> Choose Database file (.mdf) under type .
Browse -> go to your App_Data folder, and choose the DB.
copy the connection string created in App.config to web.config.
bye.

How do I copy my database

I am working on visual studio 2010 and i have a database in Server Explorer that i can see that is not in the App_data in the solution explorer.. I need to copy it somewhere to upload it to the host..
I think the database is suitable for SQL server2005 , cause that is the only sql server version installed on my computer with the vs2010.
Here are my connection string:
<add name="YourGuruDB" connectionString="Data Source=DIMA-00AA1DA557;Initial Catalog=model;Integrated Security=True" />
You can back up the database by right click on db and choose back up. Restore it on your host /web server.
I would prefer to export you database schema and mandatory data as sql scripts using SSMS (SQL Server Management Studio) then run the script on the host.
Here is a great tutorial about it http://blog.sqlauthority.com/2007/08/21/sql-server-2005-create-script-to-copy-database-schema-and-all-the-objects-stored-procedure-functions-triggers-tables-views-constraints-and-all-other-database-objects/
EDIT: if you are using VS2010 there is a new feature in the deployment called "Package/Publish SQL" allow you to package your SQL DB. Here is a tutorial how to use it http://rachelappel.com/deployment/database-deployment-with-the-vs-2010-package-publish-database-tool/
Erm. your connection string says the database in use is model. That's a special database in SQL Server that's used a template for new databases (that's why you can't detach/copy). You're going to have all sorts of problems if you stick with that name.
But DO NOT rename it. You're going to have to create a new database - which will have everything you've put in model in it. Then remove everything you've added to model.
You should now be able to detach your new database and move it elsewhere.
Select you database in SQL Managment Studio.Then Tasks\Detach.
After this you can copy the database files to another distination. To make you database on-line again, just do Tasks\Attach.
P.S It's only the one among other approaches to accomplish your task.

Resources