'C# DBConnection.Open() Invalid Cast Exception

I am trying to connect to a database using the DBConnection class. Everything works fine on the development pc as well as some other computers, however there are some computers which gives an Invalid Cast Exception when trying to call the DBConnection.Open() method.

I am using a DbProviderFactory and assign the DBConnection = DbFactory.CreateConnection() after setting DbFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");

So in short:

this.DbFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");
this.Connection = this.DbFactory.CreateConnection();
this.Connection.Open(); // Throws the exeption

I have looked around and read that I should use Microsoft.Data.SqlClient instead, ie. this.DbFactory = DbProviderFactories.GetFactory("Microsoft.Data.SqlClient");. However when I use this and run the program I get the error - 'Unable to find the requested .Net Framework Data Provider. It may not be installed.'



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source