Why do I have 2 instances of SQL Server? - c#

I'm new to SQL Server and I'm trying to learn MVC for some school projects. I have a program that creates a DB with Code-first approach in Entity framework. But when I tried to find it in my SQL Server Management Studio I didn't find it. So I checked in Visual Studio 2013 "SQL Server Object Explorer" and find that I have 2 SQL Server instances. Since I'm only writing to one SQL Server instance I decided to delete the one at the top. But as soon as I restart my program it's there again. How can I only have 1 instance to write to ? The DB I'm writing to is the one at the bottom "TestDB".
Edit
Adding DB Context by request

In Your code currently EF not use at all ConnectionString you expecting.
This is how this should look like:
<connectionStrings> <add name="UserContext" connectionString="Server=.\SQLEXPRESS; User Id=Seeya; Password=;Initial Catalog=CodeFirstTest; Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>
and now Your Context:
public class UserContext : DbContext
{
public UserContext()
:base("UserContext")
{
}
//REST OF YOUR CODE
}
The other instance is because EF craeted SQLCompact, when nothing was given as parameter to base method of Context.

Related

Entity Framework MigrateDatabaseToLatestVersion CREATE DATABASE permission denied in database 'master' error

I've been looking through questions on here but have yet to come across anything that deals with my problem, apologies if this is a duplicate and I've missed something.
I have an ASP.Net MVC project with Entity Framework Code First.
In my Dbcontext I have;
public Context() : base("DatabaseName")
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
}
In my web config I have;
<connectionStrings>
<add name="DatabaseName" connectionString="connsection string is here"/>
</connectionStrings>
When my application is deployed, I get the error
'CREATE DATABASE permission denied in database 'master'.' as soon as
it tries to access the Context for the first time.
What I don't understand is how to stop it trying to create a database and just use the connection string that I have given it. The database already exists (It's on shared hosting so I don't have much control over it) and I know the connection string is correct as I have Hangfire installed in the same application, using the same connection string and it has successfully created the tables but for some reason EF doesn't create the tables in the database and instead tries to create one, which it cannot do.
Entity Framework is installed in the same project as the config file, in fact, it's a single project application.
I've tried creating another database and adding a second connection string in case Hangfire was preventing EF from using it but had the same issue. I've also tried putting the full connection string directly into :base("") on the context, but it has no effect.
try getting connectionString by name
public Context()
:base("name=DbConnection")
{
}
in Web.config file add
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=serveraddress;Persist Security Info=False;User ID=usename;Password=pass;Initial Catalog=databasename" providerName="System.Data.SqlClient" />
</connectionStrings>

Web API & Entity Framework, Where to specify Database connection?

I am going to try and explain this issue as clear as I can.
I start with two projects:
Project One: Data model
A repository class that wraps a DbContext that has a single DbSet: RentalListings
This DbContext uses the default settings, so that when I save changes it saves to local DB.
Project Two: Console App
Contains a console application that when runs, instantiates an instance of the repository class.
Then it creates multiple "RentalListings" and saves them to the repository.
So far so good. After running the console app I check the local DB SQL object explorer, and my repository class has successfuly saved to this db.
Now, I want a way to access this inserted data via a Web API. So I add:
Project Three: Web API
I create a new controller class and add a single GET action method to fetch all listings.
When I run the API project, I can hit the action method, which looks like:
[HttpGet]
public IEnumerable<RentalListing> GetAllListings() {
StatsRepository repository = new StatsRepository(new StatsContext());
return repository.GetRentalListings();
}
via the correct URL. However I am getting the following error returned:
Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.
Now, from searching the web I think the issue is that it doesn't know how to access the database??? And that I should specify a connection string in the Web.config file in my Web API project.
Questions:
1) How did my console app, that doesn't specify a connection string, create a mdf database using my repository class?
2) Why doesn't the same work for my web api project? can't it just use the repository to fetch the database, just like the console app did?
Look forward to hearing the replies, thanks in advance!
Q :1. How did my console app, that doesn't specify a connection string, create a mdf database using my repository class ?
A :1. It is by default.If you didn't specify the connection string on console app then it uses your context class namespace plus name of the context class to create a db.
e.g.
Context class namespace = MyDbContextNameSpace
Name of the context class = MyContext
Then your DB name will be like this : MyDbContextNameSpace.MyContext.
Note : If SQL Express is installed then the database is created on your local SQL Express instance (.\SQLEXPRESS). If SQL Express is not installed then Code First will try and use LocalDb ((localdb)\v11.0).
You can read more about it here : Building an Initial Model & Database
Q :2. Why doesn't the same work for my web api project? can't it just use the repository to fetch the database, just like the console app did?
A :2. When you talk to EF through Http/s,you have to provide the connection string on web.config file. Otherwise EF doesn't know how to do that.That is by design.
e.g.
MyContext.cs
public class MyContext : DbContext
{
public MyContext() : base(“name=MyContextConn”)
{
}
public DbSet<Blog> Blogs { get; set; }
}
web.config
<connectionStrings>
<add name=“MyContextConn“ connectionString=“conndetails”
providerName=“System.Data.SqlClient“ />
</connectionStrings>
The DbContext class can definitely be responsible for 'specifying a connection string', as you put it, but the reason it is most commonly found in a config file is so that different connection strings can be specified for different configurations. For example, your Web.Debug.config connection string might point to an instance of SqlExpress that you have installed on your development box and the Web.Release.config connection string might point to a Sql instance contained in Azure.
Specifying a connection string in your config file isn't necessarily going to fix the issue. The connection string can specify a username and a password. If you put those in to the connection string then it will most likely work. For example <add name="DefaultConnection" connectionString="Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" providerName="System.Data.SqlClient" />
The issue you are experiencing is most likely due to the fact that the console application is running under the context of the Windows user launching the application. It is using those credentials to connect to the database. I'm assuming that your console, webapi app and sql are all installed/running on the same machine and that your user is the only one that you use to log in to sql(again assuming you are using SSMS). The web application though is most likely being run through IIS or IISExpress which is run under a different context by default(I believe IUSR for IIS). If you would like to have your connection string use integrated security(to keep your username and password out of your configs -- which is generally considered a good practice) like this: <add name="DefaultConnection" connectionString="Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=True" providerName="System.Data.SqlClient" /> then you would want to setup the context that the application is being run under by updating the user the apppool is running under. You would do this by updating the app pool identity and then making sure that the web application is using that app pool.
Hope this helps.

Entity Framework 4.1 code first model compatibility issue after changing database from embedded to SQL Server Express

Hello Entity Frameworks Gurus!!
I've been following the official tutorial and have started a small project with it. I've started using SQL Server Compact Edition and have decided to change it to a SQL Server Express database.
After changing my connectionstring
<add name="SchoolContext" connectionString="Data Source=|DataDirectory|Registration.sdf" providerName="System.Data.SqlServerCe.4.0"/>
<!-- <add name="SchoolContext" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=True;Initial Catalog=SchoolRegistration;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>-->
it started throwing this error:
Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention
has been added to the DbModelBuilder conventions.
What I don't comprehend is that I have an Initializer which implements the DropCreateDatabaseIfModelChanges
public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
and added the Initializer to the Global.asax.cs application_start()
Database.SetInitializer<SchoolContext>(new SchoolInitializer());
So after my error I deleted the SQL Server Compact .sdf file and switched back to its connection string and all the changes and all fixtures where put in it.
Why not SQL Server Express?
Something I am missing? Or should I have created another context for the new connection string and refactor my Initializer? Thanks for reading this
EF checks whether the model and the database are in sync by checking the values in the EdmMetadata table. In your case that table is missing in the database. But you are using the DropCreateDatabaseIfModelChanges initializer. Hence EF can not determine whether the model has been changed to execute the initializer.
If you want to use that initializer you need to let EF create the database with the EdmMetadata table (meaning dropping your express database so that EF can recreate it for you from your connectionString). Otherwise remove the initializer and manually do the changes to the database or use EF migrations.

EF Code First - {"CREATE DATABASE permission denied in database 'master'."}

I just want to quickly spin up the default database in my development environment.
How is the easiest way to get around this problem?
I once faced this problem and resolved it. The key is using SQL authentication instead of Windows'. This is the clearest way to specify the default db.
Try connection string in this way:
<add name="MFCConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MFC.mdf;Initial Catalog=MFC;Integrated Security=false;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
remember to set default db of sa from master to MFC, and Integrated security = false.
BTW, sa is normally disabled, so enable and test it in sql server management studio first.
Run your application under account which has permission to create database on your development SQL server. If you are using SQL authentication specify credentials for SQL login in your connection string which has this permission. By default admin account specified during SQL server installation has this permission but you can add it to other logins as well.
This may be of use to anybody stumbling across this question, as I did, when looking for an answer to the error. These steps should be all you need and I've copied code in you can paste to get it running quickly.
I'm using Code First, tried using 'create-database' but got the error in the title.
Closed and re-opened (as Admin this time) - command not recognised but 'update-database' was so used that. Same error.
Here are the steps I took to resolve it:
1) Opened SQL Server Management Studio and created a database "Videos"
2) Opened Server Explorer in VS2013 (under 'View') and connected to the database.
3) Right clicked on the connection -> properties, and grabbed the connection string.
4) In the web.config I added the connection string
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=MyMachine;Initial Catalog=Videos;Integrated Security=True" providerName="System.Data.SqlClient"
/>
</connectionStrings>
5) Where I set up the context, I need to reference DefaultConnection:
using System.Data.Entity;
namespace Videos.Models
{
public class VideoDb : DbContext
{
public VideoDb()
: base("name=DefaultConnection")
{
}
public DbSet<Video> Videos { get; set; }
}
}
6) In Package Manager console run 'update-database' to create the table(s).
Remember you can use Seed() to insert values when creating, in Configuration.cs:
protected override void Seed(Videos.Models.VideoDb context)
{
context.Videos.AddOrUpdate(v => v.Title,
new Video() { Title = "MyTitle1", Length = 150 },
new Video() { Title = "MyTitle2", Length = 270 }
);
context.SaveChanges();
}
I have the same problem with EF 6.0 and code first. If you have multiple projects with different connection strings and running update-database from the package manager console even if you select the right default project, Visual studio reads the connection string from the start up project and so if there is no connection on that start up project then the error is permission denied..
You can solve it by set the right project as start up project (just for updte database).

How do I connect to an existing database in ASP.NET MVC?

I'm just starting to learn C# and ASP.NETMVC, but every example I've found puts the database in the App_Data folder. I don't want to do this.
I'd like to create a new version of Nerd Dinner and move the connection string to the web.config, but I can't find any examples on how to do it. My database is called NerdDinner and I'm using SQL Server Express.
What's the correct syntax to add the new connection string to my web config? Does this have any effect on creating LINQ to SQL classes?
I always go to http://www.connectionstrings.com/ when I forget how a connectionstring is written.
Standard security SQL Server 2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Here is an article on MSDN talking about How to: Read Connection Strings from the Web.config.
You have a section almost at the top in your Web.config called connectionstrings, it could look something like this:
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
I would recommend however that you also look in to Entity Framework which is an abstraction between your code and the database, it makes it easier to work with "objects" in your database. You can find an introduction to ADO.NET Entity Framework here. But first of all you should focus on getting your connection up and running to your database using the information at the top.
An additional way to have your context 'point' to the connextionsStrings line in the web.config file is to try this constructor.
public class MainDB : DbContext
{
public MainDB() : base ("name=DefaultConnection")
{
}
public DbSet<User> Users { get; set;}
}
Then change the name to DefaultConnection in the web.config file.

Categories