I have multiple SQL databases with the same schema .Say(Database1,Database2....)
How do i dynamically select a database in Entity framework model in runtime?.Since they have the same schema, it does not make sense to import all the data models before hand.
You can change database connection string like this:
DataModelContainer context = new DataModelContainer(
ConnectionOperation.CreateEntityConnection());
And this is CreateEntityConnection Method:
internal static EntityConnection CreateEntityConnection()
{
// Start out by creating the SQL Server connection string
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source. The IP address network address
sqlBuilder.DataSource = System.Configuration.ConfigurationManager.AppSettings["Connection"];
// The name of the database on the server
sqlBuilder.UserID = "sa";
sqlBuilder.Password = "12345";
sqlBuilder.InitialCatalog = "DatabaseName";
sqlBuilder.IntegratedSecurity = true;
sqlBuilder.MultipleActiveResultSets = true;
// Now create the Entity Framework connection string
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl";
// Create and entity connection
EntityConnection conn = new EntityConnection(entityBuilder.ToString());
return conn;
}
Related
I am getting this error:
Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.
Instance failure.
here is my code :
void ConnectToDb()
{
connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = #"(localdb)\MSSQLLocalDB";
connStringBuilder.InitialCatalog = "WRESTLING.MDF";
connStringBuilder.Encrypt = true;
connStringBuilder.ConnectTimeout = 30;
connStringBuilder.AsynchronousProcessing = true;
connStringBuilder.MultipleActiveResultSets = true;
connStringBuilder.IntegratedSecurity = true;
string temp = #"Server=EC2AMAZ-FN5N011\\MSSQLSERVER;Database=C:\APP_DATA\WRESTLING.MDF;Trusted_Connection=True;";
string temp1 = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=C:\APP_DATA\WRESTLING.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(temp);
comm = conn.CreateCommand();
}
When you want to connect to a local database file (.mdf) you can use the following connection string syntax with AttachDbFilename:
#"Data Source=(local);AttachDbFilename=C:\APP_DATA\WRESTLING.MDF;Integrated Security=True;Connect Timeout=30;"
I have the following C# code that should allow me to modify (alter) a stored procedure of mine:
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString);
ServerConnection srvCon = new ServerConnection(sqlCon);
sqlCon.Open();
Server srv = new Server(srvCon);
Database db = srv.Databases[sqlCon.Database];
StoredProcedure sp = new StoredProcedure(db, "spRDLDataFetcher");
sp.TextMode = false;
sp.AnsiNullsStatus = false;
sp.QuotedIdentifierStatus = false;
sp.TextBody = "SELECT blah FROM MyTable WHERE ID=1";
sp.Alter();
However, the sp.Alter()call throws this error:
Microsoft.SqlServer.Management.Smo.FailedOperationException: 'Alter failed for StoredProcedure 'dbo.spRDLDataFetcher'. '
Inner Exception: InvalidSmoOperationException: You cannot perform operation Alter on an object in state Creating.
What am I missing in order to get it to alter (update) that stored procedure?
Alright so I found out why it was not updating it. Seems, for whatever reason, it needed sp.Refresh(); First before I overwrote the textBody.
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString);
ServerConnection srvCon = new ServerConnection(sqlCon);
sqlCon.Open();
Server srv = new Server(srvCon);
Database db = srv.Databases[sqlCon.Database];
StoredProcedure sp = new StoredProcedure(db, "spRDLDataFetcher");
sp.TextMode = false;
sp.AnsiNullsStatus = false;
sp.QuotedIdentifierStatus = true;
sp.ImplementationType = ImplementationType.TransactSql;
sp.Schema = "dbo";
sp.Refresh(); //What was needed to make work
string orgSPText = sp.TextBody;
sp.TextBody = "SELECT blah FROM MyTable WHERE ID=1";
sp.Recompile = true;
sp.Alter();
The sp.Recompile = true; really is not needed. It will work without it but I like to keep that in there just for kicks and giggles.
Currenlty I am using the following connection string to connect to oracle database
string Source = new OracleConnectionStringBuilder()
{
DataSource = #"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = YOURHOST)(PORT = 1521)))(CONNECT_DATA =(SID = TESTORACLE)))",
}.ConnectionString;
private IDbConnection databasecon= new OracleConnection(Source);
I have no idea how to specify that connect using os authentication
Finally found the way to create Non TNS windows authentication connection stringstring Source = new OracleConnectionStringBuilder()
{
DataSource = #"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = YOURHOST)(PORT = 1521)))(CONNECT_DATA =(SID = TESTORACLE)))",
UserID = #"/",
}.ConnectionString;
private IDbConnection databasecon= new OracleConnection(Source);
without user id and password just use UserID = #"/" for windows authentication
I am not able to create a backup of database saved in location like C:\database\mydb.mdf
error : Unable to create a backup
Backup sqlBackup = new Backup();
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "Archive";
sqlBackup.Database = databaseName;
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
//ServerConnection connection = new ServerConnection(serverName, userName, password);
ServerConnection connection = new ServerConnection(serverName);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
string dataBaseName = #"C:\database\mydb.mdf";
string serverName = #"Data Source=.\SQLEXPRESS;Integrated Security=True;User Instance=True";
string destinationPath = "C:\\mydb.bak";
Maybe I am passing wrong variables?
Please can anyone verify it and post me the right solution
thnx in advance.
PS: database is not password protected and can use mixed authentication
First of all - I guess some of your parameters are wrong:
ServerConnection connection = new ServerConnection(serverName);
Here, you need to pass just the server's name - so in your case, do not send in your whole connection string - just .\SQLExpress
As for your database name - I don't know if you can use SMO to backup an "attached" MDF file in SQL Server - normally, this would be the database name (the name of the database only - no file name, no extension) when the database is on the server.
string dataBaseName = #"C:\database\mydb.mdf";
So my suggestion here would be:
attach this MDF file to your SQL Server instance (which you have installed anyway)
give it a meaningful name, e.g. mydb
then use just the database name as your value here:
string dataBaseName = "mydb";
With these points in place, your code does work just fine in my case, at least...
TextBox1=Server Name
TextBox2=Db Name
TextBox3=User Name
TextBox4=Password
I declared as a variable "Server Name,dbname,user name,password".My question is; I want to test my sql connection on another machine by them using.
How can I do that with c#?
//// SqlConnection conn = new SqlConnection
////("Data Source="+ server +";Initial Catalog=DATA;Persist Security Info=True;User ID=sa");
You could use the SqlConnectionStringBuilder for this scenario:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = TextBox1.Text.Trim();
builder.InitialCatalog = TextBox2.Text.Trim();
builder.UserID = TextBox3.Text.Trim();
builder.Password = TextBox4.Text.Trim();
string result = builder.ConnectionString;
This builds up the connection string and returns it as a result in the end.
Also: you might want to use more descriptive names for your textboxes! tbxDataSource, tbxInitialCatalog etc. would be much better than TextBox1, TextBox2 etc.
little modified pranay's answer
bool TestConnection()
{
SqlConnection conn = new SqlConnection(string.Format(#"user id={0}; password={1};Data Source={2};
Trusted_Connection=yes;
Initial Catalog={3};
connection timeout=30", userName,password,serverName,database));
try
{
conn.Open();
return true;
}
catch (Exception e)
{
return false;
}
}