I have a simple query that loads data from two tables into a GUI. I save the downloaded data to a widely Clients currentlySelectedClient
object Clients currentlySelectedClient
.
using (var context = new EntityBazaCRM()) { currentlySelectedClient = context.Kliencis.Include("Podmioty").FirstOrDefault(d => d.KlienciID == klientId); if (currentlySelectedClient != null) { textImie.Text = currentlySelectedClient.Podmioty.PodmiotOsobaImie; textNazwisko.Text = currentlySelectedClient.Podmioty.PodmiotOsobaNazwisko; } else { textNazwa.Text = currentlySelectedClient.Podmioty.PodmiotFirmaNazwa; } }
So now, if I wanted to:
1) Save the changes made by the user, how can I do this? Should I prepare something on the database side? How to process several tables (some data goes here, some there)? My current code seems to be writing. KlienciHaslo is just great, but it doesn't affect Podmioty at all. I tried different combinations, but no luck.
2) Add a new client to the database (as well as save information in the appropriate tables)?
currentClient.Podmioty.PodmiotOsobaImie = textImie.Text; // not saved currentClient.Podmioty.PodmiotOsobaNazwisko = textNazwisko.Text; // not saved currentClient.KlienciHaslo = "TEST111"; // saved using (var context = new EntityBazaCRM()) { var objectInDB = context.Kliencis.SingleOrDefault(t => t.KlienciID == currentClient.KlienciID); if (objectInDB != null) { // context.ObjectStateManager.ChangeObjectState(currentClient.Podmioty, EntityState.Modified); //context.Podmioties.Attach(currentClient.Podmioty); context.Kliencis.ApplyCurrentValues(currentClient); // update current client //context.ApplyCurrentValues("Podmioty", currentClient.Podmioty); // update current client } else { context.Kliencis.AddObject(currentClient); // save new Client } context.SaveChanges(); }
How can I reach both?
Change answer (doesn't save anything):
currentClient.Podmioty.PodmiotOsobaImie = textImie.Text; // no save currentClient.Podmioty.PodmiotOsobaNazwisko = textNazwisko.Text; // no save currentClient.KlienciHaslo = "TEST1134"; // no save using (var context = new EntityBazaCRM()) { if (context.Kliencis.Any(t => t.KlienciID == currentClient.KlienciID)) { context.Kliencis.Attach(currentClient); // update current client } else { context.Kliencis.AddObject(currentClient); // save new Client } context.SaveChanges(); }
source share