I have create MVC5 application and I have local DB ,currently I have entered data
to the table and I able to see that in the MDF file under server explorer ->data connections ,now I want to read it via API below and its not working i've provided the ID which I have in the table and I get null ,I think maybe that I need to provide the connection string to the API but not sure how ,any idea how to do that?
This is DB context from the model definition
public class PersonModelDbContext : DbContext
{
public PersonModelDbContext()
: base("Connection1")
{
}
This is the read API
private PersonModelDbContext db = new PersonModelDbContext();
public Person GetPrviderData(string id)
{
Person person = db.Person.Find(id);
return person;
}
This is the connection string in the WEB CONFIG FILE
<connectionStrings>
<add name="Connection1" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Person.mdf;Initial Catalog=Persons;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Update - in addition I try with the following without success ,I got error:
db.Database.Connection.ConnectionString = #"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Person.mdf;Initial Catalog=Persons;Integrated Security=True";
An exception of type 'System.Data.DataException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: An exception occurred while initializing the
database. See the InnerException for details.
You could try setting your connection string to more this format since it is local
<add name="DataBaseConnectionName"
connectionString="Data Source=[ServerNameHere];User ID=[DatabaseLogonID/Probably sa];Password=[DatabasePassword];Initial Catalog=TheNameoftheLocalDB;"
providerName="System.Data.SqlClient" />
You could try that to establish a connection also don't keep the [brackets] in the connection string.
Related
I'm trying to create two databases with SQL Server 2014, Entity Framework. One is created "automatically" with asp.net identity and the other one I create using a seed method in Configuration.cs.
Both have the same SQL login in the connection string, but only the identity database is created. For the other one, the following error occurs:
The underlying provider failed on Open. [...]
System.Data.SqlClient.SqlException: Cannot open database "dbname" requested by the login. The login failed.
Here are the connection strings:
<connectionStrings>
<add name="AntContext"
connectionString="Database=dbname;User Id=user; Password=mypw;"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection"
connectionString="Database=dbnameidentity;User Id=user; Password=mypw;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Checking in SQL Server Management Studio, the database dbnameidentity is created and even populated with seeding data from Configuration.cs, but for the other one the login fails.
I have no idea why this happens. I'll provide more information if necessary. Thanks.
Here's the head of my seed method.
protected override void Seed(IdentityDbContext context)
{
var antcontext = new DataContext.AntContext();
If you don't have an initialiser set for your context. This means it will not try to create the database. If you want to ensure the DB is created, then you can use the CreateDatabaseIfNotExists initialiser, for example:
public class AntContext: DbContext
{
public AntContext(): base("AntContext")
{
Database.SetInitializer<AntContext>(new CreateDatabaseIfNotExists<AntContext>());
}
//snip
}
I have a weird error when I move to SQL Server Express from LocalDb. This is the error:
This operation requires a connection to the 'master' database. Unable
to create a connection to the 'master' database because the original
database connection has been opened and credentials have been removed
from the connection string. Supply an unopened connection.
This error occurs when I tried to CreateDatabaseIfNotExists on context initialization.
Here is my connection string:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=AlvinCMS;MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient" />
Here is my context:
public class AlvinCMSMigrationDBContext : DbContext
{
public AlvinCMSMigrationDBContext() : base("DefaultConnection")
{
Database.SetInitializer<AlvinCMSMigrationDBContext>(new CreateDatabaseIfNotExists<AlvinCMSMigrationDBContext>());
}
I initiate the database on the global.asax:
protected void Application_Start()
{
//Check And Init Database
Alvin_CMS.App_Start.DatabaseConfig.Initialize();
And finally this is my initialization code:
public static void Initialize()
{
Alvin_CMS.Models.AlvinCMSMigrationDBContext migrationDB = new Models.AlvinCMSMigrationDBContext();
try
{
if (!migrationDB.Database.Exists())
{
migrationDB.Database.Initialize(false); //ERROR HERE!
AlvinCMSExtension.Models.AccountDBContext accountDB = new AlvinCMSExtension.Models.AccountDBContext();
accountDB.Database.Initialize(false);
SetDefaultValue(migrationDB);
}
migrationDB.Database.Initialize(false);
}
catch (Exception e)
{
migrationDB.Database.Delete();
AlvinCMSExtension.Helper.Log(e);
}
}
I do not know what is wrong with my code, because it was fine when I use LocalDb, but now I cannot even connect to my database.
Here are my attempts to fix this issue:
I put Persist Security Info = True;Trusted_Connection=False; - still producing the same error.
I tried to change Database.SetInitializer<AlvinCMSMigrationDBContext>(null); But I need to create the database if not exist, so this is not a fix for me
You can use connection string as shown below.
<add name="DefaultConnection" connectionString="Server=localhost; Database=
AlvinCMS;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
In my case "StoreMan" is the database name. Replace it with your own.
<add name="StoreMan" providerName="System.Data.SqlClient" connectionString="Server=localhost; Database=StoreMan;Trusted_Connection=True;Integrated Security=True;MultipleActiveResultSets=True"/>
I am trying to run this code:
var db = Database.Open("DBNAME");
var q = "Select Name From Table";
#foreach(var row in db.Query(q)){
<li> #row.Name </li>
}
But I get the error System.InvalidOperationException: Connection string "DBNAME" was not found.
So I went in to WebMatrix 3 and added this database under Other Connections and working fine in the WebMatrix3 app. But the connection string I fed WebMatrix to add to the connections was not appended to the web.config file, and I still get this error, so not sure what else to do? Suggestions?
Also, do DB connections like this have to be closed? I did not see a close statement in the example I took this from, which is from here: http://www.w3schools.com/aspnet/webpages_database.asp
Update: I added the following setting in web.config:
<connectionStrings>
<add name="DBNAME" connectionString="server=(local)\Server;database=DBNAME;uid=myUser;password=myPass;" />
</connectionStrings>
And now I get the following error instead: System.ArgumentException: Keyword not supported: 'server'. <-- this error shows up for the #foreach line
You can just add the connection string to your web.config file. Depending on what kind of database you use.
If you use SQL Server you can use something like this:
<configuration>
<connectionStrings>
<add name="DBNAME" connectionString="Data Source=.\Server;Initial Catalog=MyDatabase;User ID=Username;Password=Password" providerName="System.Data.SqlClient"/>
</connectionStrings>
<configuration>
More on connection strings here: http://www.connectionstrings.com/
Edit:
Yes Database connection should be closed! It implements IDisposable interface so you should use the using clause.
Here is an example
using (Database db = Database.Open("DBNAME"))
{
// Do your database stuff here
}
It will call the Dispose mehtod when it reaches the end of using clause. Dispose() will close the connection upon many other things.
So I have Solution with two projects. The first projects should act as a Data Access Layer so there in the app.config file I have this:
<connectionStrings>
<add name="BloggingContextCF"
connectionString="provider=System.Data.SqlClient;
provider connection string="
data source=*****\SQLEXPRESS;
initial catalog=CodeFirst.Blogging;
integrated security=True;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
The second Project is a ASP.NET Web Forms project, where I removed the default connection string pointing to the (local) instance leaveing only one connection string, the one from the first Data Access Layer project. Which actually works and the database is created on my SQL 2008 R2 server, but instead of the desired (and expected) database name - CodeFirst.Blogging the name is DataAccessLayer.BloggingContextCF where DataAccessLayer is the name of the project and BloggingContextCF is the class extending DbContext.
What I need to change in my connection string so I can get the desired name?
Try
public BloggingContextCF ():base("CodeFirst.Blogging") {}
make the connections string like
Point it to sql client
providerName="System.Data.EntityClient"
to
providerName="System.Data.SqlClient"
For full connection string do it like
<add name="BloggingContextCF" connectionString="Server=YOUR_SERVER;Database=DATABASE_NAME;User ID=USER_ID;Password=PASSWORD;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
For more connectionstring example follow the link
and don't forget to modify your dbcontext
public class YourContext : DbContext
{
public UsersContext()
: base("BloggingContextCF"){ }
}
I have a local ASP.NET MVC 3 Windows Azure Project where I use a local instance of MSSQL Express for my emulator.
In my web.config I have the following connection string:
<add name="ExampleDb" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ExampleDb;User Instance=true;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
For debugging purposes I have the following in my WebRole.cs file:
public override bool OnStart()
{
ExampleDb context = new ExampleDb();
context.ExampleItemEntries.Add(new ExampleItem() { ExampleItemId = 1, Att1 = "1", Att2 = "2" });
context.SaveChanges();
return base.OnStart();
}
When I perform this action I can actually see the content in my code-first generated database (using Entity Framework). Database: ExampleDb, Table: ExampleItem.
However, doing the exact same thing in ExampleController does NOT update the database. Instead this data goes somewhere else (I have no idea where). When I visit my controller via the browser I can upload data and look at it but it is not stored in my ExampleDb database, only data sent from WebRole.cs is in the database.
Any ideas what's causing this behaviour?
ExampleDb.cs looks like this:
public class ExampleDb : DbContext
{
public ExampleDb() : base("ExampleDb") { }
public DbSet<ExampleItem> ExampleItemEntries { get; set; }
}
Your connection string contains 'User Instance=True'. This means that SQLEXPRESS uses a user instance to store your data. This is a completely different instance of SQL Server that contains a new set of databases.
I assume the code in WebRole.cs is run in a different user account than the code in ExampleController. When the ExampleController is run under a user account that is not an administrator, a user instance is used...
So when you remove 'User Instance=True' from your connectionstring and assign the proper access rights to your SQLEXPRESS database instance, that would solve the problem.
In CodeFirst Model you should define the connection string in the web.config first as below:
<connectionStrings>
<add name="ExampleDbConnection"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
database=ExampleDb;
AttachDBFilename=|YouDataDirectory|yourdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
<connectionStrings/>
The DbContext class constructor accepts a name-value pair specifiying connection-string name in web.config. So you can reference this connection string in your context:
class ExampleDb : DbContext
{
public ExampleDb() : base("name=ExampleDbConnection") { }
...
}
This code does work fine in a ASP.NET MVC Web Role so you can try as above.