0

Does it make sense to create new object before trying to save object that I already have loaded but with more then one Context?

After lots of tries and errors this code seems to work fine. Basically it's regetting values for Konsultanci and Szkolenie with the current Context based on objects that are read from ObjectListView.

        var listaDoPodmiany = new List<SzkolenieUczestnicy>();
        if (listaUczestnikow.GetItemCount() > 0) {
            foreach (SzkolenieUczestnicy currentUczestnik in listaUczestnikow.Objects) {
                using (var context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)) {
                    if (currentUczestnik.SzkolenieUczestnicyID == 0) {
                        var nowy = new SzkolenieUczestnicy {
                            Konsultanci = context.Konsultancis.First(p => p.KonsultantNazwa == currentUczestnik.Konsultanci.KonsultantNazwa),
                            Szkolenie = context.Szkolenies.First(p => p.SzkolenieID == varSzkolenie.SzkolenieID),
                            SzkolenieUzytkownik = currentUczestnik.SzkolenieUzytkownik,
                            SzkolenieUzytkownikData = currentUczestnik.SzkolenieUzytkownikData,
                            UczestnikPotwierdzilUdzial = currentUczestnik.UczestnikPotwierdzilUdzial,
                            UczestnikPrzybyl = currentUczestnik.UczestnikPrzybyl
                        };


                        context.SzkolenieUczestnicies.AddObject(nowy);
                        context.SaveChanges();
                        listaDoPodmiany.Add(nowy);
                    } else {


                        context.SzkolenieUczestnicies.Attach(currentUczestnik);
                        context.ObjectStateManager.ChangeObjectState(currentUczestnik, EntityState.Modified);
                        context.SaveChanges();
                        listaDoPodmiany.Add(currentUczestnik);
                    }
                }
            }
            listaUczestnikow.ClearObjects();
            listaUczestnikow.SetObjects(listaDoPodmiany);
        }

This seems to solve lots of problems I was getting about multiple contexts. But is it good approach? Will there be much impact on speed since I guess Konsultanci and Szkolenie will be read another time from SQL?

This is continuation (or more like conclusion from multiple questions I asked before):

Community
  • 1
  • 1
MadBoy
  • 10,213
  • 18
  • 88
  • 146
  • If `currentUczestnik` has ID = 0 it was probably not yet added to any context so why to create it again? – Ladislav Mrnka Feb 01 '12 at 10:04
  • It's a part of larger code for reupdating... I have updated post to not cause confusion. Also the currentUczestnik has ID=0 but Szkolenie and Konsultanci are already taken from different contexts. Hence the problems.. – MadBoy Feb 01 '12 at 10:07
  • 1
    Why do you use multiple contexts at the same time? – Steven Feb 01 '12 at 10:08
  • Yes but still I don't understand why do you need to create new instance for adding. – Ladislav Mrnka Feb 01 '12 at 10:09
  • Because I loaded `Consultants` in from one Table to one ObjectListView, then user assigns this `Consultant` from that ObjectListView to another ObjectListView under different Object called TrainingConsultants. And when saving new object is created called Szkolenie which is saved under context and assigned to TrainingConsultants as well. So in the end there's new object called TrainingConsultants that have 2 objects referenced 2 it which were get using different context. The code is more or less in the 1st link in Question. – MadBoy Feb 01 '12 at 10:13
  • It's not same time. There's one method to get object Consultant it uses Context1 (`using context1`), then there's another method saving `Training` (`using context2`) then there's 3rd value supposed to be saved which uses `Training` and `Consultant` objects and those are assigned like: `TrainingParticipants.Consultant = Consultant;` `TrainingParticipants.Training = Training` and when I do go to save TrainingParticipants I get errors about multiple contexts. – MadBoy Feb 01 '12 at 10:16

1 Answers1

4

Does it make sense to create new object before trying to save object that I already have loaded but with more then one Context?

No. But it shows you have a design problem in your application. You shouldn't have to deal with multiple contexts for the same objects.

I think you have a problem with your contexts lifetime. This isn't an easy issue to solve, but here is an article that could help you. See also here.

My opinion is that contexts should have the shortest lifetime as possible. Long-running contexts are generally a bad practice, as you'll quickly encounter issues in your application (memory leak, problems when dealing with multi-threading or concurrency...etc.)

If you have a 3-tiers architecture, then you really should expose stateless services and create a new context per request. If you're accessing directly the database from your application (2-tiers application), for instance a Winform application that requests the DB directly, shorten the lifetime of your context as much as possible if you can't do stateless requests.

Final word: creating new contexts has a very small overhead, and it won't lead to performance issues 99% of the time.

ken2k
  • 45,682
  • 8
  • 105
  • 160
  • Well I am using `using` per each get / set of any object. Then I try using .Detach on the end of dealing with object but I was still getting problems on the last mile when trying to attach those 2 objects into one final object and try to save it. – MadBoy Feb 01 '12 at 10:24
  • @MadBoy Why do you need to re-attach objects that come from another context with your new object? For instance, if it's about a one-to-many relation between your entities, you should simply use the key of the object, not the object itself. – ken2k Feb 01 '12 at 10:28
  • Yes. It's about one-to-many relation. I tried using EnityKey and EntityReference only and it was still giving me some pain. I guess I'll try to redo code again and fight this. Don't want to make mistakes on the begining and carry them over. Since I'm trying to write this program the RIGHT WAY and I will for sure will be reusing the code I write now. Unless it's something else to set then EntityKey and EntityReference? – MadBoy Feb 01 '12 at 10:31