0

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?

Community
  • 1
  • 1
MadBoy
  • 10,213
  • 18
  • 88
  • 146
  • [This](http://stackoverflow.com/questions/3653009/entity-framework-and-connection-pooling/3653392#3653392) can explain you why you should not use context for anything else than single business unit of work (single threaded logical business operation). – Ladislav Mrnka Feb 01 '12 at 09:34

1 Answers1

2

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 ?

Yes, yes it will. A context is basically a thin layer on top of a database connection - which is not thread safe, so you cannot reuse the same context across threads. What you are looking for is a unit of work within which you use the same context, but once that unit of work is completed you dispose the context. Since you use your own repository implementation you will have to build the unit of work on top of those repositories.

BrokenGlass
  • 149,257
  • 27
  • 271
  • 318