private static void UpdateRecord(int carId) { using (var context = new AutoLotDbContext()) { var carToUpdate = context.Cars.Find(carId); if (carToUpdate != null) { Console.WriteLine(context.Entry(carToUpdate).State); carToUpdate.Color = "Blue"; Console.WriteLine(context.Entry(carToUpdate).State); context.SaveChanges(); } } }
private static void ExplicitLoading() { using (var context = new AutoLotDbContext()) { context.Configuration.LazyLoadingEnabled = false; //to guarantee nothing more loaded foreach (var car in context.Cars) { context.Entry(car).Collection(x => x.Orders).Load(); foreach (var order in car.Orders) { Console.WriteLine(order.OrderId); } } foreach (var order in context.Orders) { context.Entry(order).Reference(x => x.Car).Load(); } } }
private static void RemoveRecord(int carId) { using (var context = new AutoLotDbContext()) { var carToDelete = context.Cars.Find(carId); //first load entity and then delete it if (carToDelete != null) { context.Cars.Remove(carToDelete); } Console.WriteLine(context.Entry(carToDelete).State); //Deleted context.SaveChanges(); } }
private static void RemoveRecordUsingEntityState(int carId) { using (var context = new AutoLotDbContext()) { var carToDelete = new Car{ CarId = carId }; //var car = context.Cars.Find(carId); //to fail context.Entry(carToDelete).State = EntityState.Deleted; //will fail if item with the same key already tracked try { context.SaveChanges(); } catch (DbUpdateConcurrencyException ex) //will fail if no entity with such Id { Console.WriteLine(ex); } } }
public int Save(T entity) { _ctx.Entry(entity).State = EntityState.Modified; return(SaveChanges()); }