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).
Related
I am trying to make a sql server connection. I have used ASP.net web form template which is having its own login and register Ui. I just have to use my sql Server name and the database name in the connection configuration. I had googled and read regarding the sql connection. I FOUND something like this in WEbconfig i have to alter..
<connectionStrings >
<add
name="myConnectionString"
connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
It does not work if i use it . Should i use SqlConnection con = new SqlConnection(strcon); in my login page.if in case, then where ? While in this template i have something like..
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
.....
I ma bit confused please educate me or guide me in the right way.
I have a server name xyz-1-2, database name: data123, username: abcd123 and password: asdf123.
I am trying to connect to one database and visualize the data.
I assume you are using at least Visual Studio 2013 to create the web form project by using the default template available there.
Now, let's take a look on the database setup first, as it seems like this is the one you're asking about.
After the project generation, the default connection string in the web.config file, usually look like this :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebMVCWithAuth-20180220020657.mdf;Initial Catalog=aspnet-WebMVCWithAuth-20180220020657;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
When will the connection string be used actually in the project? Please examine the screenshot below :
It's not necessary to change the connection's name here, but please do adjust the connectionString value, in the later stage.
So, where's the actual database file resides, you may ask? Actually, it is hidden in the App_Data folder, and you will not see it until click the "Show All Files" icon just below the "Solution Explorer" header, as shown in the following screenshot :
And how do you browse the content of this database? Look into the left-most of the VS editor and find a toolbox "Server Explorer", and there you are. See this screenshot?
Now by the time you end reading this, you should have an idea how to have your own user manager database, based on this template.
Oh, and one more tip : you can actually copy this local database to a real server and attach it to the database server so you may continuously maintain the database in a more secure environment.
Hope it helps.
Trying to connect ASP.Net code first project to Azure. At this stage it launching application online as project was published. I can browse pages, but when I try to create new dynamic pages it gives me an error. My project works fine locally.
I uploaded project using Azure SDK and used info from azure such as the server name and connection string. Here it is:
<connectionStrings>
<add name="PhClub" connectionString="Server=tcp:phclub.database.windows.net,1433;Initial Catalog=PhClub;Persist Security Info=False;User ID=myloginname for azure;Password=******;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" />
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-PhClub-20170304023453.mdf;Initial Catalog=aspnet-PhClub-20170304023453;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
However, there was one thing which cached my eye but i don't know what it means and how to fix it. In App_data folder i have two databases, but in the publish window I see three of them:
As you can see something is wrong with last one.
Here how it looks in preview window:
Looking for your advise since this is my first solo project. Thank you in advance!
Try adding providerName="System.Data.SqlClient" at the end of the PhClub connection string.
If we create <customErrors mode="Off"/> in our web.config file, then we could see the details error message. We could get more info about how to troubleshoot a web app in Azure App Service using Visual Studio
We could debug it with following 2 ways:
1.Make sure that the connectionstring for dbcontext is the azure sql connectionstring
2.Make sure that Azure sql could be accessed by azure service.(Allowed default). More detail info about azure sql firewall please refer this document.
Try to ignore the # symbol with \ before or double it like ##.
Because with azure # separates loginName#server.
An alternative is to create a new user/login in the database, which's username doesn't contain a # and use this user in the connection string.
Thanks for all answers. It seems that problem was in connection string login credentials, i deleted web app, server and database, recreated it again with new simple login name. Changed all of the login name and password in connection strings. This way i got rid of the error.
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.
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.
I have gone through the steps to publish my web app using database first on the azure portal.
However, when I publish I get this error message:
Code generated using the T4 templates for Database First and Model
First development may not work correctly if used in Code First mode.
To continue using Database First or Model First ensure that the Entity
Framework connection string is specified in the config file of
executing application. To use these classes, that were generated from
Database First or Model First, with Code First add any additional
configuration using attributes or the DbModelBuilder API and then
remove the code that throws this exception.
My connection string in the web.config after it has been modified by publish:
<add name="MySiteEntities" connectionString="metadata=res://*/MySite.csdl|res://*/MySite.ssdl|res://*/MySite.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:**********.database.windows.net,****;initial catalog=MySite;user id=username#**********;password=*******;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
My context (generated by edmx):
public partial class MySiteEntities : DbContext
{
public MySiteEntities()
: base("name=MySiteEntities")
{
}
...
I am very confused becuase it seems like entity framework is trying to use code first rather than database first.
UPDATE:
I just tried using the same connection string locally and the web app seems to run fine. The web app does connect to the remote database fine. It is only when I publish to azure it fails.
Read my answer to a similar question at Entity framework work locally but not on azure.
If you made the same "mistake" I did, this is what's happening ... the Azure-deployed app isn't finding your connection string "MySiteEntities" inside your web.config. Instead, at the time your created your Azure Web Site (or Cloud Service or whatever), you created an associated Azure SQL Database and gave its connection string the exact same name, "MySiteEntities". This latter connection string is a "plain" connection string without Model/Database-first metadata references, and so is being treated as a Code-First connection by EF, which then complains about the conflict. See Code First vs. Database First for an explanation of this distinction.
It should be:
<connectionStrings>
<add name="MyDatabaseModelEntities"
connectionString="metadata=res://*/MyDBModel.csdl|res://*/MyDBModel.ssdl|res://*/MyDBModel.msl;
provider=System.Data.SqlClient;
provider connection string="
Data Source=<provideServerName>.database.windows.net;
Initial Catalog=MyDatabase;
Integrated Security=False;
User ID=<provideUserID>;
Password=providePassword>;
MultipleActiveResultSets=True;
Encrypt=True;
TrustServerCertificate=False""
providerName="System.Data.EntityClient"/>
</connectionStrings>
I changed connection string to remote (Azure) on my local web.config, then remove all set connection strings during publishing and publish web.config. It rewrites remove web.config. Then return connection string on local web.config to local connection. It works fine now.