I'm brand new to using MVC, and I'm trying to use an initializer to initialize data into my DB when the application is first started. Here is what I've got in Global.asax.cs:
System.Data.Entity.Database.SetInitializer(new MyAppInitializer());
MyAppContext db = new MyAppContext();
db.Database.Initialize(true);
In Web.config, here is my connection string:
<connectionStrings>
<add name="MyAppContext"
connectionString="data source= MyServer; Integrated Security=True; database=MyDatabase"
providerName="System.Data.SqlClient"/>
This is using MS SQL 2008 R2. My Initializer looks like this:
public class MyAppInitializer : DropCreateDatabaseAlways<MyAppContext>
{
protected override void Seed(MyAppContext context)
{
var organizations = new List<Organizations>
{
new Organizations { OrgName = "AT", OrgPhone = 5093333433, OrgOfficeLocation = "ITB", OrgPointOfContact = "Tony", OrgIsActive = 1 },
new Organizations { OrgName = "Libraries", OrgPhone = 5093331122, OrgOfficeLocation = "Holland-Terrell", OrgPointOfContact = "Herald", OrgIsActive = 1 }
};
organizations.ForEach(s => context.Organizations.Add(s));
context.SaveChanges();
I made sure I closed my connection to the server and database in SQL Server Management Studio, but multiple people have access to this DB, although none should be using it right now. How can I get it so I can initialize this data in my DB? Thanks!
Edit: I've already got the DB created on the server, but it is completely empty (no tables, procedures, etc). Would this cause an issue?
I faced a similar issue today when using MVC codefirst. After 20 mins of trying out various stuff I noticed that, the "Server Explorer" tab in Visual Studio had a connection open to my database. After I "closed" the connection in the server explorer tab of visual studio, the code was able to run and automatically recreate the database.
In SSMS run something like this...
USE master -- be sure that you're not on MYDB
ALTER DATABASE MYDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE MYDB;
As described by Vardhini... close DB connection in Server Explorer.
In the SSMS "Delete" window make sure that "Close existing connections" is checked.
Closing all existing connections of the database in visual studio server explorer and SQLManagement studio solved the problem for me.
My observations are:
Cannot be logged in to application
Cannot be connected to db with Server Explorer
Cannot be connected with SSMS
Then the application rebuild DB even when Database.SetInitializer<DbContext>(new DbInitializer()); is in public DbContext(); - NOT as other answears stand to put it into Application_Start();
Related
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb; Database=ABC; Trusted_Connection=True; MultipleActiveResultSets=true"}
I am working with ASP.NET Core MVC. I have this connection string in my appsettings.json file but it doesn't seem to work. While running "dotnet ef database update" from cmd, I am getting this error keyword not supported: 'server.'. What's wrong with it?
Apologies! In my ConfigureServices method in Startup.cs, I was using SQLite database provider
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")))
I changed it to the following, and it worked with my connection string.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
The connection string should start of with Data Source=.
In Visual Studio if you open the SQL Server Object Explorer and click on the database you are wanting to connect to. The connection string will be displayed in the Properties window. The connections string should look something like this for localDb
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DbName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=Fals
Can someone please help me fix my connection string? I am an absolute beginner using the MS SQL Management Studio but I am an experienced C# programmer. I am trying to figure out how to connect to a local database on my PC. I just installed SQL server 2012 Express today and I created a table with one row of data. I am trying to access that table from a C# program. I've been looking for help calling a stored procedure (with no parameters) and it seems like I am doing everything right, but I get an exception error "Could not find stored procedure 'GetCustomers'." I have also tried changing my the procedure name to "dbo.GetCustomers" and also "SqlTest.dbo.GetCustomers" and also "SqlTest.GetCustomers", but nothing seems to work. Clearly I am not connecting to my database correctly. I've been working on this for 4 hours now so it's time for me to stop and find help. I think all I need is a good connection string and the proper syntax for the procedure.
Connect c = new Connect();
if(c.MakeConnection())
{
try
{
DataSet data = new DataSet();
SqlDataAdapter adaptor = new SqlDataAdapter();
//changed to use stored procedure
adaptor.SelectCommand = new SqlCommand("GetCustomers", c.MyConnect);
adaptor.SelectCommand.CommandType = CommandType.StoredProcedure;
//adaptor.SelectCommand.ExecuteNonQuery();//this throws an exception.
adaptor.Fill(data);//this throws an exception.
}
catch (Exception e)
{
Logger.WriteMessage(e.Message);
}
finally
{
c.CloseConnection();
}
My connection class contains the following:
string connection = Properties.Settings.Default.DatabaseConnectString;
sqlConnection = new SqlConnection(connection);
sqlConnection.Open();
Connection string I have tried which seem to connect OK:
Server=(localdb)\v11.0;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Integrated Security=true;
My Database name is SqlTest. I have tried several variations in my connection string, but most of them throw a logon failed exception error. I verified that my windows user ID has admin privileges for the database.
Connection strings I have tried which cive me logon errors:
Server=(localdb)\v11.0;Initial Catalog=SqlTest;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Initial Catalog=dbo;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Integrated Security=true;
I guess all I needed was some sleep. ;-)
I needed to set all of my SQL server services to Automatic. For some reason, they were set to manual, and so they were not started.
Then, I also needed to set the correct server name in my connection string. This is the same server name that is used to logon when starting SQL Server Management Studio. Here is a connection string that connects and accesses the correct database and table:
Server=RAPHAEL\SQLEXPRESS;Database=SqlTest;Trusted_Connection=Yes;
I am developing an asp.net mvc3 application using Visual Studio 2010.I need to access the database.
I wrote the connection string as
SqlConnection conn = new SqlConnection("Data Source=./App_Data/Abcd.mdf;Integrated Security=True;User Instance=True");
But, when I run the code, I get an error: 40 - Could not open a connection to SQL Server.
From the SQL Server Configuration Manager, I enabled TCP/IP but I still get the same exception.
I also tried changing the connection string to
SqlConnection conn = new SqlConnection("System.Configuration.ConfigurationManager.ConnectionStrings.ConnectionString");
But I got an exception that said "Format of the initialization string does not conform to specification starting at index 0."
How do I overcome this problem?
Thank you in advance for your help.
This will depend on the type of database you are using: SQL Express or SQL Developer/Standard. If you use SQL Express you may take a look at the following article illustrating different connection strings. For example:
Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Abcd.mdf;Integrated Security=True;User Instance=True
If you are using the full version of SQL Server, your database is no longer stored in the App_Data folder. It is managed by SQL Server. Checkout the following site for connection strings in this case depending on your scenario.
Example:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
SqlConnection conn = new SqlConnection("Data Source=.\sqlexpress;database=dbname;AttachDbFilename=|DataDirectory|\Abcd.mdf;Integrated Security=True;User Instance=True");
or
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("webconfigconnectionname").ConnectionString);
In VS click on server explorer and add the connection
when the connection has been setup right click on the established connection and select properties
you will get the properties window open. In that window select the connection string, which you can use in the sqlconnection
I am following the example here: http://developer.db4o.com/Forums/tabid/98/aft/10114/Default.aspx to setup my MVC2 app with db4o using an HttpModule. I also have a LINQPad instance open to query the data as I develop. The web app seems to work like a charm, but LINQPad keeps getting DatabaseFileLockedExceptions until I close down the web server.
As I said, I'm using the HttpModule from Gamlor practically verbatim (using ClientServer instead of embedded is the only difference), and here's my LINQPad code:
01 void Main()
02 {
03 using(var server = Db4oClientServer.OpenServer(db4opath, 0))
04 {
05 using(var db = server.OpenClient()){
06 var result = (from Object o in db select o);
07 result.Dump();
08 }
09 }
10 }
11
12 private string db4opath = #"C:\blah\blah\blah\blah.db4o";
The LINQPad code works fine if the web server isn't running.
What am I doing wrong?
When you open the db4o database it locks the database-file to prevent corruption. This means while your server is running, the database file is locked and no other process can access it. (Yes there's a way to disable this, but that will almost certainly corrupt the database)
Is you're webserver also running client server mode? If thats the case you could connect the the running db4o-instance. You also can first try to connect and only if you fail directly open the server?
If you're only using the embedded-client server in your ASP.NET application, you could change that for debugging-purposes to real client server. The ASP.NET only uses the embedded clients. But it lets you connect with LINQ-Pad.
Answer for the comment:
You need to open a fully server, which supports clients which connect over the network. For example:
// in your application
int PortNumber = 8888;
using(var server = Db4oClientServer.OpenServer("database.db4",PortNumber))
{
server.GrantAccess("debug-user","debug-pwd");
// application uses embedded client:
using(var container = server.OpenClient())
{
// your application does stuff
}
}
And then in LINQPad:
using(var client = Db4oClientServer.OpenClient("localhost",8888,"debug-user","debug-pwd"))
{
// do stuff
}
I'm in a hoo-ha with my boss as I can't shift to using newer technologies until I have proof of some outstanding issues. One of the main concerns is how repositories deal with connections. One of the supposedly largest overheads is connecting and disconnecting to/from the database. If I have a repository where I do the following:
public ContractsControlRepository()
: base(ConfigurationManager.ConnectionStrings["AccountsConnectionString"].ToString()) { }
with the class like so:
public class ContractsControlRepository : DataContext, IContractsControlRepository
with functions like:
public IEnumerable<COContractCostCentre> ListContractCostCentres(int contractID)
{
string query = "SELECT C.ContractID, C.CCCode, MAC.CostCentre, C.Percentage FROM tblCC_Contract_CC C JOIN tblMA_CostCentre MAC ON MAC.CCCode = C.CCCode WHERE C.ContractID = {0}";
return this.ExecuteQuery<COContractCostCentre>(query, contractID);
}
Now if in my controller action called _contractsControlRepository.ListContractCostCentres(2) followed immediately by another call to the repository, does it use the same connection? When does the connection open in the controller? When is it closed?
Cheers
EDIT
I'm using hand-written LINQ as suggested by Steve Sanderson in his ASP.NET MVC book.
EDIT EDIT
To clarify, I'm using LINQ as my ORM, but I'm using raw SQL queries (as shown in the extract above) for querying. For example, here's a controller action:
public ActionResult EditBusiness(string id)
{
Business business = _contractsControlRepository.FetchBusinessByID(id);
return View(business);
}
I'm not opening/closing connections.
Here's a larger, more complete extract of my repo:
public class ContractsControlRepository : DataContext, IContractsControlRepository
{
public ContractsControlRepository()
: base(ConfigurationManager.ConnectionStrings["AccountsConnectionString"].ToString()) { }
public IEnumerable<COContractCostCentre> ListContractCostCentres(int contractID)
{
string query = "SELECT C.ContractID, C.CCCode, MAC.CostCentre, C.Percentage FROM tblCC_Contract_CC C JOIN tblMA_CostCentre MAC ON MAC.CCCode = C.CCCode WHERE C.ContractID = {0}";
return this.ExecuteQuery<COContractCostCentre>(query, contractID);
}
Then ContractsControlRepository is instantiated in my controller and used like _contractsControlRepository.ListContractCostCentres(2). Connections aren't opened manually, DataContext deals with that for me.
Without knowing the details of your ORM and how it connects the SQL database drivers will connection pool. When a connection is closed it is released back to the pool and kept open for X number of seconds (where X is configurable). If another connection is opened and all the parameters match (the server name, the application name, the database name, the authentication details etc.) then any free, but open connections in the pool will get reused instead of opening a brand new connection.
Having not read the book in question I don't know what "manual linq" actually is. If it's manual means you're getting the tables back youself then obviously you're doing the connection open/close. Linq to SQL will use a new connection object when a statement is finally executed at which point connection pooling comes into play - which means a new connection object may not be an actual new connection.