In this question I was having problem with saving objects that had foreign keys because Objects
were build from multiple Objects
connected to each other thru foreign keys but they were loaded using different context each time. For example:
using (var context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)) {
IQueryable<Konsultanci> listaKonsultantow = from k in context.Konsultancis
select k;
}
Then somewhere else in the code there would be more context
used to get more object types like Persons, Training, you name it.
Then there would be code to save it (simplified):
using (var context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)) {
if (context.Szkolenies.Any(t => t.SzkolenieID == currentSzkolenie.SzkolenieID)) {
context.Szkolenies.Attach(currentSzkolenie);
context.ObjectStateManager.ChangeObjectState(currentSzkolenie, EntityState.Modified);
} else {
context.Szkolenies.AddObject(currentSzkolenie);
}
context.SaveChanges();
}
Usually after trying to save it there would be multiple error messages
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
or
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects
and few others.
So to resolve it I have declared private EntityBazaCRM context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM);
on top of my class and reused it all the time without putting it into using
. Thanks to this action I didn't have to attach anything prior to saving or anything. I was just using same context and attached any foreign keys I wanted using currentUczestnik.Szkolenie = szkolenie;
and currentUczestnik.Konsultanci = consultants;. It saved without problems.
To the question:
It works for a small GUI that I have now that isn't overcomplicated. But what if I introduce multithreading, try to get multiple values from all over the place for different objects (load object to GUI, to ListView etc) using the same Context? Won't it blow back on me hurting me severely ?
In my old code before I found out about Entity Framework I was using:
const string preparedCommand = @"SELECT ID FROM TABLE WHERE NAME = "TEST"";
using (SqlConnection varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
using (SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader())
while (sqlQueryResult.Read()) {
string id= sqlQueryResult["id"].ToString();
}
}
which basically I was using for every single time I wanted to connect to SQL. If there was no connection, it would be established, if there was connection it would be reused and no problems with multithreading.
Can someone tell me what problems I can expect from doing it the way I found out to be working? Or maybe it's best way to do it?