EF Code first Keyword not supported: 'provider' - c#

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" />

Related

EF6 Passing Connection String to DbContext: System.ArgumentException: 'Keyword not supported: 'provider'.'

I'm trying to pass a connection string to DbContext class through it's constructor but I keep getting this exception. System.ArgumentException: 'Keyword not supported: 'provider'.'
Based on other stackoverflow posts I'm getting the connection string this way.
public string GetConnection()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = "DataSource";
sqlBuilder.InitialCatalog = "InitialCatalog";
sqlBuilder.UserID = "UserID";
sqlBuilder.Password = "Password";
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = "System.Data.SqlClient",
ProviderConnectionString = sqlBuilder.ToString()
};
return entityString.ConnectionString;
}
This is what is generated (actual credentials replaced with dummy data)
provider=System.Data.SqlClient;provider connection string="Data Source=DataSource;Initial Catalog=InitialCatalog;User ID=UserID;Password=Password"
This is the DBContext class constructor
public CustomerContext(string connectionString) : base(connectionString)
{
}
For anyone who that might be running into this error. Turns out I had to install the EF6 packages on all projects that were going to reference my repository dll.
Once the packages are installed on all projects that need it, I passed in the connection string only. Without any special formatting or providing the Provider info.
Data Source=DataSource;Initial Catalog=InitialCatalog;User ID=UserID;Password=Password

How to include work station id in entity framework database first model connection string dynamically?

I have a project that uses entity framework data model(.edmx) in it's data layer.I want to add work station id in connection string to store it during create log in database.
This is what I do:
var d = new PresentModelConnectionString();
string connectionString = d.Database.Connection.ConnectionString;
string lastCharacter = connectionString.Substring(connectionString.Length - 1, 1);
if (lastCharacter == ";")
{
connectionString += $"workstation id={Helpers.UserId.ToString()}";
}
else
{
connectionString += $";workstation id={Helpers.UserId.ToString()}";
}
d.Database.Connection.ConnectionString = connectionString;
return d;
But when it tries to connect to database and get data returns The login for user sa failed.When I remove this line:
d.Database.Connection.ConnectionString = connectionString;
It works fine.
This is the connection string:
<add name="PresentModelConnectionString" connectionString="metadata=res://*/PresentModel.csdl|res://*/PresentModel.ssdl|res://*/PresentModel.msl;provider=System.Data.SqlClient;provider connection string="data source=192.168.1.101\sql2014;initial catalog=MIS;user id=sa;password=sa_123;connect timeout=600000000;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
How can I include work station id dynamically to connection string?
Thanks
After searching several hours I found this solution, it change the connection string of entity framework database first model.As Alex recommended in comments I should use SqlConnectionStringBuilder to make connection string.
Create a partial class for model context in a separate file for adding constructor that gives connection string as parameter:
public partial class PresentModelConnectionString
{
public PresentModelConnectionString(string connectionString):base(connectionString)
{
}
}
Make connection string:
//connection string in web.config
//Data Source=192.168.1.101\sql2014;Initial Catalog=MIS_Keshavarzi_980906;user id=sa;pwd=sa_123; Connect Timeout=60000;
string connectionString =
System.Configuration.ConfigurationManager.AppSettings["ABSConnectionString"];
SqlConnectionStringBuilder connectionStringBuilder = new
SqlConnectionStringBuilder(connectionString);
connectionStringBuilder.WorkstationID = Helpers.UserId.ToString(); //get work station id
connectionStringBuilder.ApplicationName = "EntityFramework"; //set application name
For modifying the model connection string use EntityConnectionStringBuilder:
EntityConnectionStringBuilder entityConnectionBuilder = new
EntityConnectionStringBuilder();
entityConnectionBuilder.Metadata =
"res://*/PresentModel.csdl|res://*/PresentModel.ssdl|res://*/PresentModel.msl";
entityConnectionBuilder.Provider = "System.Data.SqlClient";
entityConnectionBuilder.ProviderConnectionString =
connectionStringBuilder.ConnectionString;
PresentModel should change with your model name.
Finally create a new instance of model context with this connection string:
var entityContext = new
PresentModelConnectionString(entityConnectionBuilder.ConnectionString);

Connecting to localDb in a unit test throws exception

I have a VS2013 project that talks to a Sql Server database, using EF6.1. To date, I've been running some automated tests using the Effort in-memory database.
I'm experimenting with using Sql Server's LocalDb, instead, and I'm running into problems I don't understand.
From with VS's Server Explorer, I created a new connection to a LocalDb database, and through it I created a new database, then
I brought up the properties window on the database, in Server Explorer, and copied the Connecting String to my clipboard, then
I pasted this connection string into the ConnectionString element of my test assembly's App.config,
I ran one of the tests.
I get:
System.ArgumentException: "Keyword not supported: 'data source'".
My connection string is simple:
<add name="MyDbContext"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=localDb;Integrated Security=True"
providerName="System.Data.EntityClient"
/>
And my code is equally simple:
[TestClass]
public class TestCustomers
{
private MyDbContext myDbContext = null;
private IEnumerable<customer> defaultCustomers = new []
{
new customer{customerid = "Customer 1"},
new customer{customerid = "Customer 2"},
new customer{customerid = "Customer 3"},
};
[TestInitialize]
public void init()
{
this.myDbContext = new MyDbContext();
foreach (var customer in this.defaultCustomers)
this.myDbContext.customers.Add(customer);
this.myDbContext.SaveChanges();
}
[TestMethod]
public void testAllCustomers()
{
var customers = this.myDbContext.customers;
var customerList = customers.ToList();
Assert.IsTrue(customerList.Count == 3);
}
}
Any ideas as to what might be going wrong?
You have specified the provider as System.Data.EntityClient instead of System.Data.SqlClient. Both of those require different connection string formats.
A good source for working out what to use is http://www.connectionstrings.com

Update EF5 Model ConnectionString in Runtime

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.

ObjectContext ConnectionString Sqlite

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;

Categories