Hi I noticed that if I use two edmx , and each one has it's own connection string, but they point to the same database, and server, user and password is the same, then distributed transaction is created. Is it any way to avoid it ?
You have to tell EF about the single Database connection. You can do it simply by openning the connection yourself after creating the context.
Like this :
using (var ctx = new YourEntities())
{
((IObjectContextAdapter)ctx).ObjectContext.Connection.Open();
//your other code
}
Related
I want to add a record with a specific ID into the database, but when I write and run this code, the line created starts with the number one. My ID is identity and I disable identity insert with the following code:
Db = new Entitites();
Db.Database.ExecuteSqlCommand(#"SET IDENTITY_INSERT CarName ON");
Db.CarName.Add(new MrSanadBaseDb.CarName()
{
PK_Car = 120,
Name = "",
IsDeleted = false
});
Db.SaveChanges();
Db.Database.ExecuteSqlCommand(#"SET IDENTITY_INSERT CarName OFF;");
Db.Database.ExecuteSqlCommand(#"ALTER TABLE CarName ALTER COLUMN PK_Car IDENTITY (121,1);");
But the record is not saved with ID = 120, the record is saved with ID = 1.
I work with SQL Server Compact Edition (SQL Server CE).
Identity insert is session (connection-open) scoped. Did you create the db-context with an already open connection? Or did you give it a connection string, or a closed connection? If it is opening the connection per operation: there is no session continuity, so each if the three operations is semantically unrelated, and do not share a session.
Based on that default constructor, I think it is using the "lookup default connection string, use deferred connection" approach. Try using the constructor that takes a connection instead, and make sure it is open first.
Specifically:
using var conn = // ... create connection
conn.Open();
Db = new Entitites(conn);
// ... the rest of your code
I have WPF app with Oracle DB. I use Entity Framework. Connection string:
DATA SOURCE=localhost:1521/ora;PASSWORD=1;PERSIST SECURITY INFO=True;USER ID=user
I need to connect to new DB with the same namespace, but another USER ID and PASSWORD. I can't create new connection string because USER ID and PASSWORD are unique for each user of the app. I need to run only two queries to new DB. For example
SELECT t.column1, t.column2 FROM "USER ID".tableName t;
What is the best way to do this?
Thanks
You can create a new connection string dynamically at runtime and use this one to connect to the database and run your two queries.
How to: Build an EntityConnection Connection String: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/how-to-build-an-entityconnection-connection-string
SqlConnectionStringBuilder Class: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder(v=vs.110).aspx
In my program C# program I need to create several mysql databases if they don't exist on the mysql server.
So I created a connection string to the server:
add name="ServerConnection" connectionString="Server=localhost;Port=7070;uid=root;password=pass;" providerName="MySql.Data.MySqlClient"/>
Once the databases are created how can I use the existing connection to connect to one of the databases ?
Should there be a connection string for each database on the mysql server ?
Thanks
No you don't need to create separate connectionstrings in your config file for each database you have the need to create.
You could use the, not so well known, class called MySqlConnectionStringBuilder living in the usual namespace MySql.Data.MySqlClient.
This class allows to specify any single key/value pair required by your connectionstring.
It also accepts, as a constructor parameter, a previous connection string that is internally splitted in the various key/value pairs and then it exposes these key/value pairs as properties of an instance of the MySqlConnectionStringBuilder.
This permits to change one property (the Database for example) and then rebuild a connection string with the updated values.
So for example you could write
MySqlConnectionStringBuidler mcb = new MySqlConnectionStringBuilder("yourinitialconnectionstring");
mcb.Database = "yournewdatabasename";
string newConnString = mcb.GetConnectionString(true);
using(MySqlConnection cnn = new MySqlConnection(newConnString))
{
......
}
The final call to GetConnectionString requires a boolean value set to true if you want the connectionstring returned to contain the password.
(Example based on MySql Provider 6.3.6)
I am creating 2 projects that have the same database (it's an MDF database). The first one is the map editor, and I use XNA 4 and Web Services to connect to it. The second one is the game itself and uses XNA 3.1 and Entity Data Model to connect database.
When I run the map editor and access the database, it runs properly. Bbut when I run the game and access the database, it shows an error "The underlying provider failed on Open"
I think the connection from the web service is not closed yet. But I don't know where I should close the connection.
Here is my code from the web service:
public Map AddNewMap(string username, string mapName, int sizeX, int sizeY)
{
using (BaseModelDataContext context = new BaseModelDataContext())
{
Map newMap = new Map()
{
Username = username,
Name = mapName,
SizeX = sizeX,
SizeY = sizeY,
Upload_Date = DateTime.Now,
Status = 0
};
context.Maps.InsertOnSubmit(newMap);
context.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);
context.Dispose();
return newMap;
}
}
EDIT:
Here is the entity data model code :
using (MazeEntities ent = new MazeEntities())
{
ent.Connection.Open();
return (from map in ent.Map
select map).ToList<Map>();
}
This code runs properly if I did not use the web service before. If I use the web service first, it shows an error at ent.Connection.Open();
Here is the inner exception:
Cannot open user default database. Login failed.\r\nLogin failed for user 'erkape-PC\erkape'.
Connection string for web service :
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\3DMapDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Connection string for the game:
"metadata=res:///MazeDataModel.csdl|res:///MazeDataModel.ssdl|res://*/MazeDataModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\eRKaPe\DropBox\TA\Program\3D_Map_Editor\3DMapEditorServices\App_Data\3DMapDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
For a quick check, can you try adding the following line after the using:
using (BaseModelDataContext context = new BaseModelDataContext())
{
context.Connection.Open();
OR
context.Database.Connection.Open();
// your code here
Finally I found a way to solve my problem after reading some articles.
The connection from the web service doesn't close automatically after I close the map editor. That is why I can't access my database from the game.
I have to change the connection string from both application, I set the User Instance to False. The game can access the database this way.
Please check the following post
http://th2tran.blogspot.ae/2009/06/underlying-provider-failed-on-open.html
Also please Enable for 32 Bit application in the APplication Pool of that application.
This may resolve.
You are trying to return an object (Map) which is associated with the Context. This object has the context information which can't be returned to the client.
You will need to create your own DataContract (a type having necessary properties) that you want to expose to the client.
Or you can use the POCO implementation As described here
I have a situation when some clients see the server by its local IP and some by global. So that for some of them IP is 10.0.0.4 and for some 94.44.224.132. I use ClickOnce for deployment and Entity Framework to generate the DB mapping. Now ive connection string setting in my user settings section and for each user i store his own one. After that for entity context's construction i do the following:
SomeEntities context = new SomeEntities(new EntityConnection("metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string=\"" + Properties.Settings.Default.ServerLocalConnectionString + "\""));
But there are some problems with Open/Close and Command execution after such approach. Is there some right way to store individual connection strings for every client and not overwrite them with deployment(ClickOnce is preferable)?
Found answer here.
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
if (serverName=="Local")
{
ecb.ProviderConnectionString = Properties.Settings.Default.ServerLocalConnectionString;
}
else
{
ecb.ProviderConnectionString = Properties.Settings.Default.ServerConnectionString;
}
ecb.Metadata = "res://*/";
ecb.Provider = "System.Data.SqlClient";
SomeEntities context = new SomeEntities(new EntityConnection(ecb.ToString());
It seems this works. And now i can deploy the application and leave to the user the decision to which server does he want to connect and leave that configuration after updates, because its written in user's app.config.