I need to connect to a database in Sqlite so i downloaded and installed System.Data.SQLite and with the designer dragged all my tables.
The designer created a .cs file with
public class Entities : ObjectContext
and 3 constructors:
1st
public Entities() : base("name=Entities", "Entities")
this one load the connection string from App.config and works fine.
App.config
<connectionStrings>
<add name="Entities" connectionString="metadata=res://*/Db.TracModel.csdl|res://*/Db.TracModel.ssdl|res://*/Db.TracModel.msl;provider=System.Data.SQLite;provider connection string="data source=C:\Users\Filipe\Desktop\trac.db"" providerName="System.Data.EntityClient" />
</connectionStrings>
2nd
public Entities(string connectionString) : base(connectionString, "Entities")
3rd
public Entities(EntityConnection connection) : base(connection, "Entities")
Here is the problem, i already tried n configuration, already used EntityConnectionStringBuilder to make the connection string with no luck.
Can you please point me in the right direction!?
EDIT(1)
I can do my queries if i use de parameterless constructor but i need to change the connection string, i can't use the one in my app.config.
How can i construct a valid connection string?!
Found it =)
if you use the EntityConnectionStringBuilder to specify the Metadataand the Provider and use the SqlConnectionStringBuilderto build the provider connection string and set the DataSource to your DB. You can connect =)
var con = new EntityConnectionStringBuilder()
{
Metadata = #"res://*/Db.TracModel.csdl|res://*/Db.TracModel.ssdl|res://*/Db.TracModel.msl",
Provider = #"System.Data.SQLite",
ProviderConnectionString = new SqlConnectionStringBuilder()
{
DataSource = db,
}.ConnectionString,
};
connection = con.ConnectionString;
Related
I have a WinForm application developed on one laptop connected to an SQL server on the same laptop.
I have a new laptop and have created a docker setup for an SQL server. I am looking to change the code base to use the new SQL server.
The new server is using SQL Server auth with username and password on the new laptop. The old laptop is using windows authentication on a windows installed setup. I have migrated a copy of the entire DB into my dockerised instance of the sql server.
The application has the connection settings in the app config and naturally this is for windows authentication.
My app.config is comitted to my github repository. I do not want to store the sql user/password in the app.settings, but instead I would like to get these from env variables I set on the machine.
I would also like to know how to change the format of the connection string in app.config so it works with sql server authentication.
Or maybe now I have explained what I am trying to do, there might be a better way?
My current connection strings are
<connectionStrings>
<add name="Blah.Properties.Settings.BlahConnectionString"
connectionString="Data Source=W.....R....;
Initial Catalog=Blah;
Integrated Security=True;
Connect Timeout=30;Encrypt=False;
TrustServerCertificate=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="Blah")]
public partial class BlahDBDataContext : System.Data.Linq.DataContext
I searched all code for 'AddDbContextFactory' and 'GetConnectionString'
public BlahDBDataContext() :
base(global::Blah.Properties.Settings.Default.BlahConnectionString, mappingSource)
{
OnCreated();
}
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=PCNAME;Initial Catalog=Blah;Integrated Security=True" + ";Connect Timeout=30;Encrypt=False;TrustServerCertificate=False")]
public string BlahConnectionString
{
get { return ((string)(this["BlahConnectionString"]));
}
The database context class is generated code inheriting as far as I can tell on System.Data.Linq.DataContext, as shown by this code from my application.
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="Blah")]
public partial class BlahDBDataContext : System.Data.Linq.DataContext
{
The BlahDBDataContext class provides a number of constructors. Please check for yourself for a fuller list.
For my purposes the constructor I needed was
public BlahDBDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
This requires the construction of a System.Data.IDbConnection object to hold/manage the connection details.
Therefore in my case all I needed to do was construct the connection string, for example.
string userName = EnvironmentVariables.GetValue("BLAH_USERNAME");
string password = EnvironmentVariables.GetValue("BLAH_PASSWORD");
string server = EnvironmentVariables.GetValue("BLAH_SERVER");
string database = EnvironmentVariables.GetValue("BLAH_DATABASE");
connectionString = $#"Data Source={server};Initial Catalog={database};Integrated Security=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;User ID={userName};Password={password};";
and then all thats needed is
new BlahDBDataContext(
new SqlConnection(
Program.GetDatabaseConnectionString()))
Where Program.GetDatabaseConnectionString() is.
public static string GetDatabaseConnectionString()
{
if (connectionString is null)
{
string userName = EnvironmentVariables.GetValue("BLAH_USERNAME");
string password = EnvironmentVariables.GetValue("BLAH_PASSWORD");
string server = EnvironmentVariables.GetValue("BLAH_SERVER");
string database = EnvironmentVariables.GetValue("BLAH_DATABASE");
connectionString = $#"Data Source={server};Initial Catalog={database};Integrated Security=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;User ID={userName};Password={password};";
}
return connectionString;
}
From a SOLID principles and clean coding perspective this is requires refactoring, and will be cleaned up now I have working code.
I am planning to replace the factory created connection string which is from web.config with a function generated connection string. I am confused where to make this change?
Connection String in Web config as below:
<connectionStrings>
<add name="ConnectionStringToDB" connectionString="Data Source=GTD,2431;Network Library=DBMSSOCN;Initial Catalog=WorkflowExecutionDB;User ID=Dev_FID;Password=****" providerName="System.Data.SqlClient" />
</connectionStrings>
Currently following code will call this above connection string:
DatabaseProviderFactory factory; /* enterprise data library*/
Database ConnectionStringToDB; /* database schema*/
factory = new DatabaseProviderFactory();
// Create a Database object from the factory using the connection string name.
ConnectionStringToDB = factory.Create("ConnectionStringToDB");
DbCommand dbCmd = ConnectionStringToDB.GetStoredProcCommand("SP_Name");
Suppose i need to change the connection string which is coming from web-config to function method result as like below, where i need to put the GetConnectionString() in the code? :
public static string GetConnectionString()
{
return "Data Source=GTD,2431;Network Library=DBMSSOCN;Initial Catalog=WorkflowExecutionDB;User ID=Dev_FID;Password=****" providerName="System.Data.SqlClient"
}
Following might be wrong:
ConnectionStringToDB = factory.Create(GetConnectionString());
What the is the right way?
I'm attempting to dynamically provide database credentials to my EF model. The below approach has worked in the past when using Database First. There are several similar SO questions however none seem to resolve this issue. What am I missing here?
private const string ProviderName = "System.Data.SqlClient";
var SqlConnectionStringBuilder = new SqlConnectionStringBuilder {
DataSource = this.ServerName,
InitialCatalog = this.DatabaseName,
IntegratedSecurity = true
};
var EntityConnectionStringBuilder = new EntityConnectionStringBuilder {
Provider = ProviderName,
ProviderConnectionString = SqlConnectionStringBuilder.ToString()
};
using(var db = new AuditingContext(EntityConnectionStringBuilder.ToString()))
{
var session = new Session() {
};
db.Sessions.Add(session);
//ArgumentException occurs here
//Keyword not supported: 'provider'.
}
The DbContext
public class AuditingContext: DbContext {
public DbSet <Session> Sessions { get; set; }
public DbSet <Cause> Causes { get; set; }
public AuditingContext(string connectionStringName): base(connectionStringName) {}
}
The connection string
provider=System.Data.SqlClient;provider connection string=\"Data Source=localhost;Initial Catalog=TEST_DATABASE;Integrated Security=True\"
As pointed out by DevilSuichiro, the DbContext for EF5+ is a connection string and not EntityConnectionString. This resolves the issue.
var connString = "provider=System.Data.SqlClient;provider connection string=\"Data Source=localhost;Initial Catalog=TEST_DATABASE;Integrated Security=True\"";
using(var db = new AuditingContext(connString))
{
//...
}
I was using a console application to test the Code First approach with Sql Server 2016.
My initial connectionString was :
add name="MyCodeFirstDb" connectionString="
Data Source=MyServer;
Initial Catalog=MyCodeFirstDb;
Provider=SQLNCLI11.1;
Integrated Security=SSPI;
Auto Translate=False;"
I put my "connectionStrings" section after the "entityFramework" section.
The error I got when creating a linq query was :
"Keyword provider not recognized"
I removed "Provider=SQLNCLI11.1;"
I then got the error :
"Keyword auto-translate not recognized"
I removed "AutoTranslate=False;"
I was then able to run the query and my database was created.
use Like that
<add name="TerminalA" connectionString="Data
Source=192.168.1.104;Database=ABC;Integrated Security=false;User
ID=sa;Password=pass#123;" providerName="System.Data.SqlClient" />
I have winforms app with SQL Db on my localServer. I added EF5 using Database_First.
The question is:
How to change the connection string of EF5 Model in "Runtime" using "OpenFileDialog"?
I want to provide the app with a "Feature" to let the client specify his Database Server where the app db is located.
There are two problems that need to be considered.
First DbContext has constructor that takes a user defined connection string, but this constructor is not exposed in the generated code for your context, so you have to add it in a partial file outside of the generated code.
And then the Entity Framework connection string itself differs from a typical SqlClient connection string, so you have to use EntityConnectionStringBuilder to build an appropriate connection string.
For example consider this sample code:
public partial class MyContext: DbContext
{
public MyContext(string efConnectionString):base(efConnectionString)
{
}
public static MyContext CreateContextFromAdoCS(string adoConnectionString)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = adoConnectionString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/MyModel.csdl|
res://*/MyModel.ssdl|
res://*/MyModel.msl";
var efCs = entityBuilder.ToString();
return new MyContext(efCs);
}
}
If you have an existing SqlClient connection string you can use the factory method to create an instance of your context.
Here Display a ConnectionString dialog you can see how to open a standard dialog to construct an SqlClient connection string.
Let it be in App.config
<add name="ConnectionStringNew" connectionString="Data Source=ServerName;user id=sa;Password=sasa;initial catalog=[DataBase]" />
Have a Combobox where you want to let the user to select the DataBase.
FIll the combobox with below coding.
SqlConnection con1 = new SqlConnection (ConfigurationManager.ConnectionStrings["ConnectionStringNew"].ConnectionString);
SqlCommand comm = new SqlCommand("SELECT ROW_NUMBER() OVER(ORDER BY NAME) AS ID,NAME FROM SYS.SYSDATABASES WHERE DBID > 4 ORDER BY NAME", con);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dtblDataBase);
cmbDataBase.DataSource = dtblDataBase;
cmbDataBase.ValueMember = "ID";
cmbDataBase.DisplayMember = "NAME";
Replace the DataBase Name Like below.
DataBaseName = Convert.ToString(con1.ConnectionString);
CommonVariables.strDataBaseName = DataBaseName.Replace("[DataBase]", cmbDataBase.Text.Trim());
CommonVariables.strCompanyName = cmbDataBase.Text.Trim();
I have just given a coding sample.. Customize it as you want.
I'm experimenting some difficulties trying to use Connection String Builders (ADO.NET) within LINQ to SQL. Let me show you guys what I'm trying to do:
the app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="LoremIpsum"
connectionString="Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and a snippet of the form:
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["LoremIpsum"];
if (null != settings)
{
string connection = settings.ConnectionString;
SqlConnectionStringBuilder builder =
new SqlConnectionStringBuilder(connection);
// passwordTextBox being the control where joe the user actually
// enters his credentials
builder.Password = passwordTextBox.Text;
}
LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext();
// finally some rather anecdotic LINQ sentence here:
var foo = db.Table.Single(bar => bar.Table == whatever);
On the other hand checking the Immediate Window:
?builder.ConnectionString
"Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;Password=swordfish"
I'm always getting an exception: Login failed for user 'joe'. Any ideas? Thanks much in advance.
It seems like you are trying to modify the connection string that is stored in the app.config file. When you use a no argument constructor for your data context, it reads what was configured at design time.
Try injecting your modified connection string into the constructor of the DataContext:
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"];
SqlConnectionStringBuilder builder;
LINQTOSQLDataClassDataContext db;
if (null != settings)
{
string connection = settings.ConnectionString;
builder = new SqlConnectionStringBuilder(connection);
// passwordTextBox being the control where joe the user actually enters his credentials
builder.Password =passwordTextBox.Text;
db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
} }
You're forgetting to send in the connectionstring to the DataContext constructor.
Example:
LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
You can force a DataContext to use a specific connection string with
DataContext db = new DataContext(myConnectionString);
The parameterless DataContext constructor will use a connection string from the App.config file first, then the connection string set at compile time.