private static void WorkingWithDetachedEntities(QueryContext context) { Console.WriteLine("\nClient from non-existing context"); var loadedClient = LoadAndDetach(); Console.WriteLine($"{loadedClient.Name} - {context.Entry(loadedClient).State}"); // detached loadedClient.Address = "Modified Address " + DateTime.Now; context.Entry(loadedClient).State = System.Data.Entity.EntityState.Modified; // or Unchanged Console.WriteLine($"{loadedClient.Name} - {context.Entry(loadedClient).State}"); // modified context.SaveChanges(); Console.WriteLine($"{loadedClient.Name} - {context.Entry(loadedClient).State}"); // unchanged (but added) }
private static void ExplicitLoading(QueryContext context) { Order order = context.Orders.Find(4); context.Entry(order) .Collection(o => o.Products) .Load(); var collection = context.Orders.Local; // 1 order with 2 products foreach (Product p in collection.First().Products) { Console.WriteLine(p.Name); } }
public ActionResult Edit(QueryMaster query) { try { if (ModelState.IsValid) { context.Entry(query).State = System.Data.Entity.EntityState.Modified; // context.Query.Add(query); context.SaveChanges(); } // TODO: Add update logic here return(RedirectToAction("Index")); } catch { return(View()); } }
private static void AttachingDetachingObjects(QueryContext context) { // existing client Console.WriteLine("\nExisting client"); Client client = context.Clients.FirstOrDefault(); Console.WriteLine($"{client.Name} - {context.Entry(client).State}"); // unchanged context.Entry(client).State = System.Data.Entity.EntityState.Deleted; Console.WriteLine($"{client.Name} - {context.Entry(client).State}"); // deleted context.SaveChanges(); Console.WriteLine($"{client.Name} - {context.Entry(client).State}");; // detached client.Name = "New Name"; context.SaveChanges(); Console.WriteLine($"{client.Name} - {context.Entry(client).State}"); // detached // new client Console.WriteLine("\nNew client"); Client newClient = new Client() { Name = "New Client" }; Console.WriteLine($"{newClient.Name} - {context.Entry(newClient).State}"); // detached newClient.Name = "New Client Modified Name"; Console.WriteLine($"{newClient.Name} - {context.Entry(newClient).State}"); // detached context.Entry(newClient).State = System.Data.Entity.EntityState.Added; Console.WriteLine($"{newClient.Name} - {context.Entry(newClient).State}"); // added context.SaveChanges(); Console.WriteLine($"{newClient.Name} - {context.Entry(newClient).State}"); // unchanged newClient.Name = "New Modified name"; Console.WriteLine($"{newClient.Name} - {context.Entry(newClient).State}"); // modified }