EF core: Setting a DbContext connection string without using operation UseSqlServer - connection-string

Is there a way how to set a concrete connection string into the DBContext without using the extension method SqlServerDbContextOptionsExtensions.UseSqlServer? What if I don't know a type of db server I will use?

Related

How to execute SqlCommand using OLEDB connection in SSIS script component

I am using SSIS 2019 and am able to execute SQL Command with ADO.Net Connection Manager.
I want to use OLEDB connection manager in a Script component within a Data Flow Task and I am getting the below error:
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
Can someone please let me know if we can use OLEDB Connection in SSIS script component in a Data flow.
Here is code for connection strings
public override void PreExecute()
{
string conn = this.Connections.Connection.ConnectionString;
}
I am not getting build error in script C# code. But getting error at script component.
Using a Script Component
To access a connection manager within a script component, you should first specify this connection manager from the script component editor as shown in the image below:
Then, within the script component, you should use the Connections variable to access this connection manager (In this example, the connection manager assigned name is Connection):
var constr = Connections.Connection.ConnectionString;
screenshot
Executing a SQL command using C#
Next, you should use this connection string to initiate a SqlConnection object in order to use it by a SqlCommand as follows:
using(SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Write here your SQL command", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
Make sure you added a reference for using System.Data.SqlClient to use the SqlConnection and SqlCommand objects.
Important Note: If you are using SQL authentication, you should re-add the password to the connection string since it will not be retrieved from the connection manager for security reasons.
Using a Script Task
You should first retrieve the OLE DB connection string from the connection manager using the following command:
string constr = Dts.Connections["OledbCM"].ConnectionString;
Demonstration
I added Messagebox.Show(constr) command to the script task to show how the connection string looks like once retrieved:
Helpful Links:
SSIS Script Task : ConnectionString for ADO.Net & OleDb ConnectionManager
Check OLDEDB database Connection using script task in SSIS
Update 1: SqlConnection vs. OleDbConnection
Since you are using SqlConnection class which represents a connection to a SQL Server database. You will encounter the following error while trying to use the connection string retrieved from an OleDb Connection:
Keyword not supported "Provider"
The main reason is that the OleDB connection requires that the connection string contains the provider information since it has the ability to connect to different providers such as Oracle, Excel, Access, SQL. While SqlConnection class does not support this information since it is only using the SQL Server Native client provider.
How to solve this issue?
You can simply use a System.Data.OleDb.OleDbConnectionStringBuilder object to remove this part using the following code:
string con = Dts.Connections["OledbCM"].ConnectionString;
var connBldr = new OleDbConnectionStringBuilder(con);
connBldr.Remove("Provider");
con = connBldr.ConnectionString;
Or you can use Linq: (Remember to add the System.Linq namespace)
string con = Dts.Connections["OledbCM"].ConnectionString;
con = string.Join(";", con.Split(';').Where(c =>
!c.TrimStart().StartsWith("Provider")));
References
How do I remove "Provider=..." from a connection string

Connecting Sql-database to wcf web sevice

I am trying to learn how to build a web service with WCF in .Net framework 4.5 using Visual Studio 2019, and I am trying to connect my service to a database already created which I want to do operation on through that web service, my exact question is: how to open a connection between the two things using SQlConnection class?, beacause I saw the constructors of the SqlConnection but I could't understand where can we write the address/Path of our database?
It may be a little bit stupid question, but I need a better explanasion than the one that exists on the Microsoft web site.
Here is my code, which describes a void method that creates the connection string. and then we call it every time we creat a connection.
Note: DataSource is the server address, IntitialCatalog is the database name
private void ConnectToDB(string datasource, string initialcatalog)
{
SqlConnectionStringBiulder ConnectionStringBuilder = new SqlConnectionStringBuilder()
{
DataSource = datasource,
InitialCatalog = initialcatalog,
IntegratedSecurity = true
};
SqlConnection connection = new SqlConnection(ConnectionStringBuilder.ToString());
SqlCommand command = connection.CreateCommand();
}
Obviously we can add the other available attributes to the connection string, and modify them as we want.

Connection string Error when trying to make Installation

I made EntityFramework (6) CodeFirst WinForms application
On my machine it works fine but when I'm trying to make Installation (with VS 2015 Installing projects) of my project and to run it on another machine, I get Expansion of Data Directory failed
I'm really dont understand- when I'm trying to change db name in ConnectionString to some wrong name- it still works.
My connection string in app config:
I found what was the problem. It is not enough to pass the name of connection string via Entity context constructor :base(ConnectionString). Entity context name MUST be the same as Connection string in app config. Other way EF create some another db.

C# Generic methods for database driver access in ADO.NET

I have to write a small C# program which will handle at least three differents database vendors (Oracle, Sybase ASE, SqlServer) in a dynamic way. (It will rely on customer choices to choose the database)
I decided to use "pure" managed drivers through ado.net data providers.
But, when I just try connecting, I expected code a la "One line to rule them all", just like JDBC does with :
DriverManager.getConnection(connection_string);
Instead of this, surprised, I have to write for each driver its specific code :
SqlConnection() for SqlServer
AseConnection() for Sybase
OracleConnection(), etc.
Of course, I should encapsulate -by myself- all of this inside abstract methods and dynamic loadings, but I'm wondering why such a thing doesn't already exist in .net
Mmhhh, I've got the feeling that I'm missing something
Since you have the .Net Provider for he respective database installed on the machine, you can use the DbProviderFactory, for sample:
include
using System.Data.Common;
and try something like this:
// create the provider factory from the namespace provider
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
// you could create any other provider factory.. for Oracle, MySql, etc...
// use the factory object to create Data access objects.
DbConnection connection = factory.CreateConnection(); // will return the connection object, in this case, SqlConnection ...
connection.ConnectionString = "read connection string from somewhere.. .config file for sample";
try
{
// open connection
connection.Open();
// create command to execute queries...
DbCommand command = connection.CreateCommand(); // create a SqlCommand, OracleCommand etc... depende of the provider factory configured.
// some logic
}
catch
{
}
finally
{
// close connection
connection.Close();
}
To know, what providers your application can find, you can use the DbProviderFactories.GetFactoryClasses() method to get a DataTable with details of every provider installed on the machine.

Specifying a named SQL Server instance for nhibernate

I've been making a first attempt to use fluent nHibernate on an ASP.NET MVC 3 application. Because I have multiple instances of SQL Server Express, I've been trying to specify a named instance along with the server while creating a session factory with the Fluently.Configure() method. My connection string for the database is of the format:
Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True;
This causes an nHibernate exception reading:
Format of the initialization string does not conform to specification
starting at index 19
where the index given corresponds to the slash before the instance name. This connection string works fine with Entity Framework 4. So how am I to specify the named instance I want to connect to in nHibernate?
Since you are doing that in code, you must escape the \ either by doubling it (\\) or by using a verbatim string:
connectionString = #"Server=myServerName\theInstanceName;Database=myDataBase;..."
Otherwise, \t is interpreted as the tab character.

Resources