public ActionResult Create([Bind(Include = "CarId,Make,Color,PetName,Timestamp")] Inventory inventory)
        {
            if (ModelState.IsValid)
            {
                db.Inventories.Add(inventory);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(inventory));
        }
        public ActionResult Create([Bind(Include = "CustId,FirstName,LastName,Timestamp")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Customers.Add(customer);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(customer));
        }
        public IHttpActionResult PostInventory(Inventory inventory)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Inventory.Add(inventory);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = inventory.CarId }, inventory));
        }
Example #4
0
        private static CreditRisk MakeCustomerARisk(Customer customer)
        {
            using (var context = new AutoLotEntities()) {
                context.Customers.Attach(customer);
                context.Customers.Remove(customer);
                var creditRisk = new CreditRisk {
                    FirstName = customer.FirstName,
                    LastName  = customer.LastName
                };
                context.CreditRisks.Add(creditRisk);

                var creditRiskDupe = new CreditRisk {
                    FirstName = customer.FirstName,
                    LastName  = customer.LastName
                };
                context.CreditRisks.Add(creditRiskDupe);

                //exception occurs because of adding the record twice
                try { context.SaveChanges(); }
                catch (DbUpdateException ex) {
                    WriteLine($"Db Update Exception: {ex.Message}");
                }
                catch (Exception ex) { WriteLine($"Exception: {ex.Message}"); }

                return(creditRisk);
            }
        }
Example #5
0
        private static int AddNewRecord()
        {
            var car = new Car
            {
                Make        = "Honda",
                CarNickName = "Civic",
                Color       = "Blue"
            };

            try
            {
                using (var context = new AutoLotEntities())
                {
                    context.Cars.Add(car);

                    context.SaveChanges();
                }
                return(car.CarId);
            }
            catch (Exception ex)
            {
                WriteLine(ex.InnerException?.Message);
                return(0);
            }
        }
Example #6
0
 internal int SaveChanges()
 {
     try
     {
         return(ctx.SaveChanges());
     }
     catch (DbUpdateConcurrencyException ex)
     {
         //Thrown when there is a concurrency error
         //for now, just rethrow the exception
         throw;
     }
     catch (DbUpdateException ex)
     {
         //Thrown when database update fails
         //Examine the inner exception(s) for additional
         //details and affected objects
         //for now, just rethrow the exception
         throw;
     }
     catch (CommitFailedException ex)
     {
         //handle transaction failures here
         //for now, just rethrow the exception
         throw;
     }
     catch (Exception ex)
     {
         //some other exception happened and should be handled
         throw;
     }
 }
        //Added a helper AddNewRecord() to insert a new record by using EF.
        private static int AddNewRecord()
        {
            // Add record to the Inventory table of the AutoLot database.
            using (var context = new AutoLotEntities())
            {
                try
                {
                    // Hard-code data for a new record, for testing.
                    var car = new Car()
                    {
                        Make = "Yugo", Color = "Brown", CarNickName = "Brownie"
                    };

                    //DbSet<TEntity> has Add().
                    //With this, I add car object which is created above to Cars property.
                    //And it is stored in memory in DbSet<Car> type.
                    //In memory, DbSet<Car> = car1, car2, ..
                    context.Cars.Add(car);

                    //I put DbSet<Car> which is put by new car just above, when I SaveChanges() of DbContext, EF does that task on behalf of myself.
                    //After finish this task, DB is changed.
                    context.SaveChanges();

                    // On a successful save, EF populates the database generated identity field.
                    //The CarId of the new record is showing.
                    //EF executes a SELECT statement on behalf of myself to get CarId value, even if I don't do anything to get that value from DB
                    return(car.CarId);
                }
                catch (Exception ex)
                {
                    WriteLine(ex.InnerException.Message);
                    return(0);
                }
            }
        }
Example #8
0
 internal int SaveChanges()
 {
     try
     {
         return(_db.SaveChanges());
     }
     catch (DbUpdateConcurrencyException e)
     {
         // Генерируется, когда возникает ошибка, связанная с параллелизмом.
         // Пока что просто повторно сгенерировать исключение.
         throw;
     }
     catch (DbUpdateException e)
     {
         // Генерируется, когда обновление базы данных терпит неудачу.
         // Проверить внутреннее исключение (исключения), чтобы получить
         // дополнительные сведения и выяснить, на какие объекты это повлияло.
         // Пока что просто повторно сгенерировать исключение.
         throw;
     }
     catch (CommitFailedException e)
     {
         // Обработать здесь отказы транзакции.
         // Пока что просто повторно сгенерировать исключение.
         throw;
     }
     catch (Exception e)
     {
         // Произошло какое-то другое исключение, которое должно быть обработано.
         throw;
     }
 }
Example #9
0
 internal int SaveChanges()
 {
     try
     {
         return(_db.SaveChanges());
     }
     catch (DbUpdateConcurrencyException e)
     {
         //parallelism error
         Console.WriteLine(e);
         throw;
     }
     catch (DbUpdateException e)
     {
         //error of update. Check inner exception.
         Console.WriteLine(e);
         throw;
     }
     catch (CommitFailedException e)
     {
         //error of transaction
         Console.WriteLine(e);
         throw;
     }
     catch (Exception e)
     {
         //other exception
         Console.WriteLine(e);
         throw;
     }
 }
Example #10
0
        private static int AddNewRecord()
        {
            // Добавить запись в таблицу Inventory базы данных AutoLot.
            using (var context = new AutoLotEntities())
            {
                try
                {
                    // В целях тестирования жестко закодировать данные для новой записи,
                    var car = new Car()
                    {
                        Make = "Yugo",
                        Color = ’’Brown", CarNickName="Brownie’'};
                    context.Cars.Add(car);
                    context.SaveChanges();
                    // В случае успешного сохранения EF заполняет поле идентификатора
                    // значением, сгенерированным базой данных,
                    return car.Carld;
                    catch (Exception ex)
                {
                    Console.WriteLine(ex.InnerException?.Message);
                    return 0;
                }
            }

        }
Example #11
0
 private static int AddNewRecord()
 {
     //Add record to the Inventory table to the AutoLot
     //Database
     using (var context = new AutoLotEntities())
     {
         try
         {
             //Hard-code data for a new record, for testing.
             var car = new Car()
             {
                 Make = "Yugo", Color = "Brown", CarNickName = "Brownie"
             };
             context.Cars.Add(car);
             context.SaveChanges();
             //On a successful save, EF populates the database generated identity field.
             return(car.CarId);
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.InnerException.Message);
             return(0);
         }
     }
 }
Example #12
0
 private static CreditRisk MakeCustomerARisk(Customer customer)
 {
     using (var context = new AutoLotEntities())
     {
         context.Customers.Attach(customer);
         //
         context.Customers.Remove(customer);
         var creditRisk = new CreditRisk()
         {
             FirstName = customer.FirstName,
             LastName  = customer.LastName,
         };
         context.CreditRisks.Add(creditRisk);
         var creditRiskDupe = new CreditRisk()
         {
             FirstName = customer.FirstName,
             LastName  = customer.LastName,
         };
         context.CreditRisks.Add(creditRiskDupe);
         try
         {
             context.SaveChanges();
         }
         catch (DbUpdateException ex)
         {
             WriteLine(ex);
         }
         return(creditRisk);
     }
 }
Example #13
0
 private static void RemoveMultipleRecords(IEnumerable <Car> carsToRemove)
 {
     using (var context = new AutoLotEntities())
     {
         context.Cars.RemoveRange(carsToRemove);
         context.SaveChanges();
     }
 }
Example #14
0
 private static void AddNewRecords(IEnumerable <Car> carsToAdd)
 {
     using (var context = new AutoLotEntities())
     {
         context.Cars.AddRange(carsToAdd);
         context.SaveChanges();
     }
 }
Example #15
0
 private static void RemoveMultipleRecords(IEnumerable <Car> carsToRemove)
 {
     using (var context = new AutoLotEntities())
     {
         //Each record must be loaded in the DbChangeTracker
         context.Cars.RemoveRange(carsToRemove);
         context.SaveChanges();
     }
 }
 static void RemoveMultipleRecords(IEnumerable <Car> carsToRemove)
 {
     using (var context = new AutoLotEntities())
     {
         //Каждая запись должна быть загружен в DbChangeTracker
         context.Cars.RemoveRange(carsToRemove);
         context.SaveChanges();
     }
 }
Example #17
0
 public void AddBook(string name)
 {
     using (AutoLotEntities entities = new AutoLotEntities())
     {
         Customer book = new Customer {
             FirstName = name
         };
         entities.Customers.Add(book);
         entities.SaveChanges();
     }
 }
Example #18
0
 internal int SaveChanges()
 {
     try
     {
         return(_db.SaveChanges());
     }
     catch (Exception ex)
     {
         throw;
     }
 }
 private static void RemoveRecord(int carId)
 {
     using (var context = new AutoLotEntities())
     {
         var carToDelete = context.Cars.Find(carId);
         if (carToDelete != null)
         {
             context.Cars.Remove(carToDelete);
             context.SaveChanges();
         }
     }
 }
Example #20
0
 private static void UpdateRecord(int carId)
 {
     using (var context = new AutoLotEntities())
     {
         Car carToUpdate = context.Cars.Find(carId);
         if (carToUpdate != null)
         {
             carToUpdate.Color = "Blue";
             context.SaveChanges();
         }
     }
 }
Example #21
0
 public static void UpdateCarRecord(int carId)
 {
     using (AutoLotEntities context = new AutoLotEntities()) {
         Car carToUpdate = context.Cars.Find(carId);
         if (carToUpdate != null)
         {
             Console.WriteLine("State Before Update: {0}", context.Entry(carToUpdate).State);
             carToUpdate.PetName = "Sabrina";
             Console.WriteLine("State After Update: {0}", context.Entry(carToUpdate).State);
             context.SaveChanges();
         }
     }
 }
Example #22
0
        private static void RemoveRecord(int carId)
        {
            ForegroundColor = ConsoleColor.Cyan;
            WriteLine($"=> Deleting Record: {carId}");

            using (var context = new AutoLotEntities()) {
                Car carToRemove = context.cars.Find(carId);
                if (carToRemove != null)
                {
                    context.cars.Remove(carToRemove);
                    context.SaveChanges();
                }
            }
        }
Example #23
0
 internal int SaveChanges()
 {
     try {
         return(db.SaveChanges());
     } catch (DbUpdateConcurrencyException ex) {
         throw;
     } catch (DbUpdateException ex) {
         throw;
     } catch (CommitFailedException ex) {
         throw;
     } catch (Exception ex) {
         throw;
     }
 }
 private static void UpdateRecord(int carId)
 {
     using (var context = new AutoLotEntities())
     {
         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();
         }
     }
 }
Example #25
0
 private static void RemoveRecord(int carId)
 {
     // Find a car to delete by primary key.
     using (var context = new AutoLotEntities())
     {
         // See if we have it.
         Car carToDelete = context.Cars.Find(carId);
         if (carToDelete != null)
         {
             context.Cars.Remove(carToDelete);
             context.SaveChanges();
         }
     }
 }
Example #26
0
 private static void AddNewRecords(IEnumerable <Car> carsToAdd)
 {
     using (var context = new AutoLotEntities())
     {
         try
         {
             context.Cars.AddRange(carsToAdd);
             context.SaveChanges();
         }
         catch (Exception ex)
         {
             WriteLine(ex.InnerException?.Message);
         }
     }
 }
Example #27
0
 private static void UpdateRecord(int carId)
 {
     using (var context = new AutoLotEntities())
     {
         // Grab the car, change it, save!
         Car carToUpdate = context.Cars.Find(carId);
         if (carToUpdate != null)
         {
             WriteLine(context.Entry(carToUpdate).State);
             carToUpdate.Color = "Blue";
             WriteLine(context.Entry(carToUpdate).State);
             context.SaveChanges();
         }
     }
 }
Example #28
0
 static void Main(string[] args)
 {
     // Строка подключения автоматически читается из конфигурационного файла.
     using (AutoLotEntities context = new AutoLotEntities())
     {
         // Добавить новую строку в таблицу Inventory, используя нашу модель.
         context.Cars.Add(new Car()
         {
             Color = "Black”,
         Make = "Pinto",
             PetName = "Pete"
         });
         context.SaveChanges();
     }
 }
Example #29
0
 private static void RemoveRecord(int carID) //extra round trip to dbase. Use EntityState for more efficiency.
 {
     // find a car to delete by primary key
     using (var context = new AutoLotEntities())
     {
         // see if we have it
         Car carToDelete = context.Cars.Find(carID);
         if (carToDelete != null)
         {
             context.Cars.Remove(carToDelete);
             context.SaveChanges();
             Console.WriteLine("Removed carID:{0}", carID);
         }
     }
 }
Example #30
0
 private static void RemoveMultipleRecords(IEnumerable <Car> carsToRemove)
 {
     using (var context = new AutoLotEntities())
     {
         try
         {
             context.Cars.RemoveRange(carsToRemove);
             context.SaveChanges();
         }
         catch (Exception ex)
         {
             WriteLine(ex.InnerException?.Message);
         }
     }
 }
Example #31
0
        private static void UpdateRecord()
        {
            // Find a car to delete by primary key.
            using (AutoLotEntities context = new AutoLotEntities())
            {
                Car carToUpdate = (from c in context.Cars
                                  where c.CarID == 2222
                                  select c).FirstOrDefault();

                if (carToUpdate != null)
                {
                    carToUpdate.Color = "Blue";
                    context.SaveChanges();
                }
            }
        }
Example #32
0
 private static void AddNewRecord()
 {
     // Add record to the Inventory table of the AutoLot
     // database.
     using (AutoLotEntities context = new AutoLotEntities())
     {
         try
         {
             // Hard-code data for a new record, for testing.
             context.Cars.Add(new Car()
             {
                 CarID = 2222,
                 Make = "Yugo",
                 Color = "Brown"
             });
             context.SaveChanges();
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.InnerException.Message);
         }
     }
 }