i have problem with entity framework with SqlServerCe.3.5 connection.
i have small project called Assets with .SDF database and entity(the model name is Main).
now,when i'm trying to connect to the entity happend something weird.
in the first time everything works fine but now i had must to added this:
if (edmConnection.State != ConnectionState.Open)
{
edmConnection.Open();
}
because the connection to the entity all time was closed.
after i added this lines,i can reach to the database and the entity,but i got this message:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
this is the stack Trace:
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString)
at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
at BL.Model.DBEntities..ctor() in C:\Users\Orel\Documents\Visual Studio 2010\Projects\Assets\BL\Model\Main.Designer.cs:line 34
at BL.Handlers.mModelHandler..ctor()
at BL.Handlers.mModelHandler.GetOnlyInstance() in C:\Users\Orel\Documents\Visual Studio 2010\Projects\Assets\BL\Handlers\mModelHandler.cs:line 30
this is my code and the app.config:
private static mModelHandler _mInstance = null;
public static DBEntities m_context = null;
public static mModelHandler GetOnlyInstance()
{
if (_mInstance == null)
{
try
{
m_context = new DBEntities(GetConnectionString());
_mInstance = new mModelHandler();
}
catch (Exception)
{
throw;
}
}
return _mInstance;
}
public static EntityConnection GetConnectionString()
{
try
{
var filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (filePath == null) throw new ArgumentNullException("filePath");
if (filePath.EndsWith("\\Assets\\bin\\Debug"))
{
filePath = filePath.Replace("\\Assets\\bin\\Debug", "\\BL\\DB.sdf");
}
var sqlCeConnectionString = string.Format("Data Source={0}", filePath);
// Create an EDM connection
EntityConnectionStringBuilder entity = new EntityConnectionStringBuilder();
entity.Metadata = "res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl";
entity.Provider = "System.Data.SqlServerCe.3.5";
entity.ProviderConnectionString = sqlCeConnectionString;
var edmConnectionString = entity.ToString();
var edmConnection = new EntityConnection(edmConnectionString);
if (edmConnection.State != ConnectionState.Open)
{
edmConnection.Open();
}
return edmConnection;
}
catch (Exception e)
{
throw;
}
}
the app.config:
<add name="DBEntities" connectionString="metadata=res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl;provider=System.Data.SqlServerCe.3.5;provider connection string='Data Source=|DataDirectory|\DB.sdf'" providerName="System.Data.EntityClient" />
i read in the fourm that the problem can be that the app.config and the connection string are not match,i tried this also and it dosen't work..
i just added an image of this:
Link
Help!
Orel
I think your connection string isn't being parsed correctly. Try using " in place of the '.
I also believe that, for SqlCE, the provider within the quotes should be provider=System.Data.SqlServerCe,3.5; instead of provider=System.Data.SqlServerCe.3.5;.
Notice the , just before the version 3.5.
Putting it all together, we have:
<add name="DBEntities"
connectionString="metadata=res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl;provider=System.Data.SqlServerCe,3.5;provider connection string= "Data Source=|DataDirectory|\DB.sdf""
providerName="System.Data.EntityClient" />
Hope this helps.
Related
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);
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 recently converted a Delphi app to C#, and I'm having an issue with an SQL connection. For some reason, when calling the CheckConnection function (shown below), IF my connection string has empty parameters, the connection is still able to .Open() without errors. Why is this? I feel like my CheckConnection function has an issue, or maybe I'm not understanding how .Open() actually works.
How it's set up - There are some textboxes that contain the hostname, user, etc. which are used as the parameters for the the connection string. Everything works fine when those are filled out correctly, but when the parameters (aka the textboxes) are all left blank, the connection still opens.
String hostname, user, password, database, protocol, query;
string connString;
IDbConnection SqlConn;
DbProviderFactory factory;
public void SetConnectionParams()
{
hostname = ServerTextBox.Text.Trim();
port = StrToIntDef(PortTextBox.Text, 3306);
user = UserIDTextBox.Text;
password = PasswordTextBox.Text;
database = DBTextBox.Text;
protocol = ProtocolTextBox.Text; //MIGHT not need
GetConnectionString(); //Get the correct connection string
}
//Gets the connection string from app.config
//The parameters for the string are all set via textboxes in diff. part of code
public void GetConnectionString()
{
if (MySqlRB.IsChecked == true) //Sets up connection for MySQL
{
var cs = ConfigurationManager.ConnectionStrings["MySQL"];
connString = ConfigurationManager.ConnectionStrings["MySQL"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = String.Format(connString, hostname, port, database, user, password);
}
else //Sets up connection for MS SQL
{
if (WindowsAuth.IsChecked == true) //If windows authentication checkbox is checked
{
var cs = ConfigurationManager.ConnectionStrings["MSSQL_WA"];
connString = ConfigurationManager.ConnectionStrings["MSSQL_WA"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = string.Format(connString, hostname, database);
}
else //don't use windows authentication
{
var cs = ConfigurationManager.ConnectionStrings["MSSQL"];
connString = ConfigurationManager.ConnectionStrings["MSSQL"].ToString();
factory = DbProviderFactories.GetFactory(cs.ProviderName);
connString = string.Format(connString, hostname, database, user, password);
}
}
}
//Supposed to check if the connection works or not
//This is working even if the connection string has empty parameters
public Boolean CheckConnection(bool check)
{
try
{
if (!CloseFirst && (SqlConn.State != System.Data.ConnectionState.Open))
{
return false;
}
else
{
using (SqlConn = factory.CreateConnection()) //make the connection
{
SqlConn.Close(); //make sure it's closed first just in case
SqlConn.ConnectionString = connString;
SqlConn.Open(); // Open the connection
if (SqlConn.State == System.Data.ConnectionState.Open)
{
SqlConn.Close();
return true;
}
else
{
return false;
}
}
}
}
catch
{
return false;
}
}
Example: Here's a connection string that's in my app.config for a sql server string:
<add name="MSSQL" providerName="System.Data.SqlClient"
connectionString="Data Source={0}; Initial Catalog={1}; User={2}; Password={3};" />
When debugging through the program, if I don't set any of the parameters, the string turns out like this:
connString = "Data Source=; Initial Catalog=; User=; Password=;"
That shouldn't be able to open right? It does though, and only when using SQL Server it seems, MySQL throws an error properly.
Edit:
Okay, turns out an error is not being thrown only when I use SQL Server windows authentication with this connection string:
<add name="MSSQL_WA" providerName="System.Data.SqlClient" connectionString="Data Source={0}; Initial Catalog={1}; Integrated Security=SSPI;"/>
Debugging through, the Data Source and Initial Catalog are empty, but the connection still opens. Not sure why this is?
The connection name 'MySqlServer' was not found in the applications configuration or the connection string is empty.
So, I have a page with a panel that will display when the connection in the web config is found and the connection is valid; using a try/catch as long as the add name"VALUE" is in the config connection strings if the server data is bad the page will load and the panel is set to invisible... I need to be able to handle the following...
If the named value in this case MySqlServer is used in the aspx; aspx.cs but not found in the config I do not want the error to occur; connection name was not found.... I just want to not show the panel like when the SqlConnection.Open fails when the name is found but data is bad...
aspx
<asp:SqlDataSource runat="server" ID="allowedIPsSqlDataSource"
ConnectionString="<%$ ConnectionStrings:MySqlServer %>"
aspx.cs
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"].ToString();
SqlConnection SqlConnection = new SqlConnection(connectionString);
SqlCommand SqlCommand = new SqlCommand();
try
{
SqlConnection.Open();
config
<connectionStrings>
<add name="NotMySqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
<add name="NotMy2SqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
</connectionStrings>
You can try :
if(ConfigurationManager.ConnectionStrings["MySqlServer"] == null) throw ...
If you're using .NET 4.5+ and have access to C# 6.0, you can make use of the null conditional operator (?) to try and get the connection string without automatically throwing an exception:
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"]?.ConnectionString;
//------------------------------------------------------------------------HERE-^-HERE-------------
if (string.IsNullOrWhiteSpace(connectionString))
{
// Don't even bother trying to open the connection.
// Log the error and either rethrow the exception (throw;) or exit from your current context (return;).
//return;
//throw;
}
// If your code has made it this far, it means you have a valid connection string. Now try to use it.
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (var sqlCommand = new SqlCommand)
{
// Do stuff.
}
}
You can check if there are any connections strings by using count.
var count = ConfigurationManager.ConnectionStrings.Count;
if (count > 0)
{
//There is at least more then one connection string.
}
Update
public static class Extension
{
public static bool HasConnectionString(this ConnectionStringSettingsCollection value, string key)
{
try
{
return value[key].ConnectionString.Length > 0;
}catch
{
return false;
}
}
}
You can use the extension as follow.
if (ConfigurationManager.ConnectionStrings.HasConnectionString("MySqlServer"))
{
//If true you know there is a valid connectionstring.
}
I have a Solution with multiple projects.
One project is my DataAccess project with 2 SQL CE databases defined, one for local users and one for company data, both with similar table structures. Public, static, readonly strings are defined for each database, and connections can be made.
Another project is my WPF project that will (eventually) display my data. To display data here, I have tried creating an Entity Context object, but nothing seems to work.
What is preventing me from accessing my data in the other project? (Currently, error states 'data source' is not defined)
How do I fix it?
AbcEntities abcContext;
public MainWindow() {
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
try {
EntityConnection ec = new EntityConnection(DataClass.AbcConnectionString);
abcContext= new AbcEntities(ec);
listbox1.ItemsSource = from c in abcContext.Customers select c;
abcCustomersBox.DisplayMemberPath = "Name";
} catch (Exception err) {
MessageBox.Show(err.Message);
}
}
For others, I found out how to do this.
In my static DataClass, I created the following routine to generate the Entity Connection String for me:
static string BuildEntityConnString(string dbFileName, string resourceData, string password) {
string resAll = #"res://*/";
string dataSource = #"Data Source=|DataDirectory|\" + dbFileName;
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Metadata = string.Format("{0}{1}.csdl|{0}{1}.ssdl|{0}{1}.msl", resAll, resourceData);
entityBuilder.Provider = "System.Data.SqlServerCe.3.5";
if (String.IsNullOrEmpty(password)) {
entityBuilder.ProviderConnectionString = dataSource;
} else {
entityBuilder.ProviderConnectionString = dataSource + ";Password=" + password;
}
using (EntityConnection con = new EntityConnection()) {
try {
con.ConnectionString = entityBuilder.ToString();
con.Open();
Console.WriteLine("{0} Entity String created.", dbFileName);
con.Close();
return con.ConnectionString;
} catch (Exception err) {
Console.WriteLine(err);
}
}
return null;
}
Notice that if there is any error, a NULL String is returned.
If anyone wants to use this, they should either place a breakpoint at the Exception, throw it, or handle it in some way. The Console.WriteLine() was just for me to debug through this.
I created Entity Connection Strings for my applications as follows:
public static readonly string EntityConnString =
BuildEntityConnString("sqlCeDb.sdf", "myModel", "abc123~Funky");
Hope others get some mileage out of this.
Explanation (more of an example, really) of how to create an EntityConnection can be found on MSDN here:
http://msdn.microsoft.com/en-us/library/bb738533.aspx
Looks pretty similar to what you have.