Ejemplo n.º 1
0
        public IHttpActionResult PutCar([FromUri] int id, [FromBody] Car car)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != car.CarId)
            {
                return(BadRequest());
            }

            _db.Entry(car).State = EntityState.Modified;

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CarExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 2
0
        public bool CreateCar(Car car)
        {
            if (!string.IsNullOrWhiteSpace(car.ModelName) ||
                !string.IsNullOrWhiteSpace(car.Marke) ||
                !string.IsNullOrWhiteSpace(car.Color) ||
                car.ProductionYear > 2000 || car.ProductionYear <= Year)
            {
                var newCar = new Car()
                {
                    ModelName      = car.ModelName,
                    Marke          = car.Marke,
                    Color          = car.Color,
                    ProductionYear = car.ProductionYear
                };

                if (newCar != null)
                {
                    _database.Cars.Add(newCar);

                    _database.SaveChanges();

                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 3
0
        public IActionResult Post([FromBody] Car carObject)
        {
            _dbContext.Cars.Add(carObject);
            _dbContext.SaveChanges();

            return(StatusCode(StatusCodes.Status201Created));
        }
Ejemplo n.º 4
0
        public ActionResult Create([Bind(Include = "CarId,Name,RegNo,Price")] Car car)
        {
            if (ModelState.IsValid)
            {
                db.Cars.Add(car);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(car));
        }
Ejemplo n.º 5
0
        public ActionResult Create([Bind(Include = "ID,Name,Mileage,Color")] Car car)
        {
            if (ModelState.IsValid)
            {
                db.Cars.Add(car);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(car));
        }
Ejemplo n.º 6
0
        public Car CreateCar(string name, BrandOfCars brand, int year)
        {
            Car car = new Car()
            {
                Name = name, Brand = brand, Year = year
            };

            _carDbcontext.Cars.Add(car);
            _carDbcontext.SaveChanges();
            return(car);
        }
Ejemplo n.º 7
0
        public IActionResult deleteCar(int id)
        {
            var car = context.Cars.Find(id);

            if (car == null)
            {
                return(NotFound());
            }

            context.Cars.Remove(car);
            context.SaveChanges();
            return(NoContent());
        }
Ejemplo n.º 8
0
        public IActionResult deleteManufacturer(int id)
        {
            var manufacturer = context.Manufacturers.Find(id);

            if (manufacturer == null)
            {
                return(NotFound());
            }

            context.Manufacturers.Remove(manufacturer);
            context.SaveChanges();
            return(NoContent());
        }
Ejemplo n.º 9
0
 internal int SaveChanges()
 {
     try
     {
         return(_db.SaveChanges());
     }
     catch (DbUpdateConcurrencyException ex)
     {
         // Генерируется, когда возникла ошибка, связанная с параллелизмом.
         // Пока что просто сгенерировать исключение повторно,
         throw;
     }
     catch (RetryLimitExceededException ex)
     {
         // Генерируется, когда достигнуто максимальное количество попыток.
         // Дополнительные детали можно найти во внутреннем исключении (исключениях) .
         // Пока что просто сгенерировать исключение повторно.
         throw;
     }
     catch (DbUpdateException ex)
     {
         // Генерируется, когда обновление базы данных потерпело неудачу.
         // Дополнительные детали и затронутые объекты можно
         // найти во внутреннем исключении (исключениях).
         // Пока что просто сгенерировать исключение повторно,
         throw;
     }
     catch (Exception ex)
     {
         // Возникло какое-то другое исключение, которое должно быть обработано,
         throw;
     }
 }
Ejemplo n.º 10
0
        internal static void Initialize(CarDbContext context)
        {
            context.Database.EnsureCreated();

            if (!context.Cars.Any())
            {
                var cars = new List <Car>();
                {
                    cars.Add(new Car()
                    {
                        Name = "AMG C63", Brand = BrandOfCars.Mercedes, Year = 2019
                    });
                    cars.Add(new Car()
                    {
                        Name = "M5 F90", Brand = BrandOfCars.Bmw, Year = 2018
                    });
                    cars.Add(new Car()
                    {
                        Name = "RS7", Brand = BrandOfCars.Audi, Year = 2017
                    });
                }
                context.Cars.AddRange(cars);

                context.SaveChanges();
            }
        }
Ejemplo n.º 11
0
        public static void Main()
        {
            using (var db = new CarDbContext())
            {
                db.Database.Migrate();

                var purchases = db.Purchases.
                                Select(p => new PurchaseResultModel
                {
                    Price = p.Price,
                    Date  = p.PurchaseDate,
                    Car   = new CarResultModel
                    {
                        VIN   = p.Car.VIN,
                        Make  = p.Car.Model.Make.Name,
                        Model = p.Car.Model.Name
                    },
                    Customer = new CustomerResultModel
                    {
                        Name = p.Customer.FirstName + " " + p.Customer.LastName,
                        Age  = p.Customer.Age
                    }
                })
                                .ToList();

                foreach (var pur in purchases)
                {
                    Console.WriteLine(pur.Customer.Name);
                    Console.WriteLine(pur.Car.Make + " " + pur.Car.Model);
                    Console.WriteLine(pur.Price);
                }

                db.SaveChanges();
            }
        }
Ejemplo n.º 12
0
        public IActionResult CreateOrder(CreateOrderVM order)
        {
            Order orderDb = new Order()
            {
                OrderId = 0, Date = DateTime.Now, ClientName = order.ClientName, CarName = order.CarName, Telephone = order.Telephone
            };

            db.Orders.Add(orderDb);
            db.SaveChanges();

            CarListVM model = new CarListVM()
            {
                cars = db.Cars.ToList()
            };

            return(View("/Views/Car/Index.cshtml", model));
        }
        public ActionResult Delete(int id)
        {
            CarDbContext db = new CarDbContext();
            var          c  = db.CarMarks.FirstOrDefault(x => x.Id == id);

            db.CarMarks.Remove(c);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public async Task SeedAsync()
        {
            db.Database.EnsureCreated();

            //StoreUser user = await userManager.FindByEmailAsync("*****@*****.**");

            //if (user == null)
            //{
            //    user = new StoreUser()
            //    {
            //        FirstName = "test",
            //        LastName = "testov",
            //        Email = "*****@*****.**",
            //        UserName = "******"
            //    };

            //    var result = await userManager.CreateAsync(user, "P@ssw0rd!");

            //    if (result != IdentityResult.Success)
            //    {
            //        new InvalidOperationException("Could not create new user in seeder.");
            //    }
            //}

            if (!db.Cars.Any())
            {
                db.Cars.Add(new Car()
                {
                    Id     = "7",
                    Type   = "Golf",
                    Model  = "Mk5",
                    Year   = "2003",
                    Engine = "1.9"
                });

                db.Cars.Add(new Car()
                {
                    Id     = "8",
                    Type   = "bmw",
                    Model  = "5",
                    Year   = "2013",
                    Engine = "3.3"
                });

                db.Cars.Add(new Car()
                {
                    Id     = "9",
                    Type   = "audi",
                    Model  = "a4",
                    Year   = "2003",
                    Engine = "1.9"
                });

                db.SaveChanges();
            }
        }
Ejemplo n.º 15
0
        public CarController(CarDbContext context)
        {
            _context = context;

            if (_context.Car.Count() == 0)
            {
                _context.Car.Add(new Car {
                    Make = "Mazda", Model = "CX-5", Year = 2016, Color = "Red"
                });
                _context.SaveChanges();
            }
        }
        public IActionResult RemoveCar(int id)
        {
            List <Car> cars = db.Cars.ToList();

            foreach (Car c in cars)
            {
                if (c.CarId == id)
                {
                    db.Cars.Remove(c);
                }
            }
            db.SaveChanges();

            List <Car> cars2 = db.Cars.ToList();
            CarListVM  model = new CarListVM()
            {
                cars = cars2
            };

            return(View("Index", model));
        }
Ejemplo n.º 17
0
        public void Delete(int?id)
        {
            if (id != null || id != 0)
            {
                var car = _database.Cars.SingleOrDefault(x => x.Id == id);

                _database.Cars.Remove(car);
                _database.SaveChanges();

                _car.DeleteCar(id);
            }
        }
        public CarSparePart SaveCarSparePart(CarSparePart cs)
        {
            CarDbContext db   = new CarDbContext();
            var          list = db.CarSpareParts.ToList();

            if (list.Contains(list.Find(x => (x.CarMarkId == cs.CarMarkId) && (x.SparePartId == cs.SparePartId))))
            {
                return(cs);
            }
            db.CarSpareParts.Add(cs);
            db.SaveChanges();
            return(cs);
        }
        public CarMark SaveCarMark(CarMark c)
        {
            CarDbContext db   = new CarDbContext();
            var          list = db.CarMarks.ToList();

            if (list.Contains(list.Find(x => x.Name == c.Name)))
            {
                return(c);
            }
            db.CarMarks.Add(c);
            db.SaveChanges();
            return(c);
        }
        public SparePart SaveSparePart(SparePart s)
        {
            CarDbContext db   = new CarDbContext();
            var          list = db.SpareParts.ToList();

            if (list.Contains(list.Find(x => (x.Name == s.Name) && (x.Code == s.Code))))
            {
                return(s);
            }
            db.SpareParts.Add(s);
            db.SaveChanges();
            return(s);
        }
Ejemplo n.º 21
0
 // Guardar los autos
 public Boolean agregarAutos(Autos _autos)
 {
     try
     {
         _context.Autos.Add(_autos);
         _context.SaveChanges();
         return(true);
     }
     catch (Exception err)
     {
         return(false);
     }
 }
Ejemplo n.º 22
0
 public void Add(Car car)
 {
     if (car.CarDailyPrice > 0 && car.CarDescription.Length >= 2)
     {
         using (CarDbContext context = new CarDbContext())
         {
             var addedCar = context.Entry(car);
             addedCar.State = EntityState.Added;
             context.SaveChanges();
         }
     }
     else
     {
         Console.WriteLine("Kriterlere uygun şekilde araba girişi yapmadınız!");
     }
 }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            using (var db = new CarDbContext())
            {
                db.Database.Migrate();

                var customer = db.Customers.FirstOrDefault();

                customer.Address = new Address
                {
                    Text = "Tintiava 15",
                    Town = "Sofia"
                };

                db.SaveChanges();
            }
        }
Ejemplo n.º 24
0
        public void Demo()
        {
            //Car mashin = new Car();
            //mashin.Name = "Volkswagen Passat";
            //mashin.Price = 50.99F;
            //mashin.State = false;
            //db.Cars.Add(mashin);
            //db.SaveChanges();

            Order sifarish = new Order();

            sifarish.StartDate = new DateTime(2019, 03, 02);
            sifarish.EndDate   = new DateTime(2019, 04, 10);
            sifarish.CarId     = 1;
            db.Orders.Add(sifarish);
            db.SaveChanges();
        }
Ejemplo n.º 25
0
        public static void Main(string[] args)
        {
            var db = new CarDbContext();

            using (db)
            {
                db.Database.Migrate();

                // AddMakesToDb(db);

                // AddModelsToOpel(db);

                // AddCarsToInsignia(db);

                // AddCarToCustomer(db);

                // AddAddressToCustomer(db);

                // GetPurchase(db);

                var result1 = db
                              .Cars
                              .FromSqlInterpolated($"SELECT * FROM Cars WHERE Price > 5000")
                              .ToList();

                db.Cars
                .Where(c => c.Price > 5000)
                .Select(c => new ResultModel
                {
                    FullName = c.Model.Make.Name
                })
                .ToList();

                var query = EF.CompileQuery <CarDbContext, IEnumerable <ResultModel> > (db => db
                                                                                        .Cars
                                                                                        .Where(c => c.Price > 5000)
                                                                                        .Select(c => new ResultModel
                {
                    FullName = c.Model.Make.Name
                }));

                var result2 = query(db);

                db.SaveChanges();
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Build several items in database, initialize the database.
        /// </summary>
        public void InitDb()
        {
            Description d1 = new Description();

            d1.Content = "This is just a content";
            Description d2 = new Description();

            d2.Content = "This is just another content";
            var n_car = new Car();

            n_car.Model = "BMW";
            n_car.Descriptions.Add(d1);
            n_car.Descriptions.Add(d2);
            _dbContext.Cars.Add(n_car);
            _dbContext.SaveChanges();
        }
Ejemplo n.º 27
0
        public static void Initial(CarDbContext context)
        {
            if (!context.Categories.Any())
            {
                context.Categories.AddRange(Categories.Select(c => c.Value));
            }

            if (!context.Cars.Any())
            {
                context.AddRange(
                    new Car
                {
                    CarName     = "BMW",
                    CarModel    = "M5",
                    YearOfIssue = 2000,
                    CarCost     = 800,
                    Category    = Categories["Седан"]
                },
                    new Car
                {
                    CarName     = "BMW",
                    CarModel    = "M4",
                    YearOfIssue = 2001,
                    CarCost     = 700,
                    Category    = Categories["Купе"]
                },
                    new Car
                {
                    CarName     = "BMW",
                    CarModel    = "M3",
                    YearOfIssue = 2002,
                    CarCost     = 400,
                    Category    = Categories["Купе"]
                }
                    );;;;
            }
            context.SaveChanges();
        }
Ejemplo n.º 28
0
        public static void Initialize(CarDbContext context)
        {
            context.Database.EnsureCreated();

            if (context.Cars.Any())
            {
                return;
            }

            var sections = new List <Car>()
            {
                new Car()
                {
                    Id = 1, CarMark = "Audi", CarModel = "Q8", CarEngine = 3
                },
                new Car()
                {
                    Id = 2, CarMark = "Audi", CarModel = "Q7", CarEngine = 3
                },
                new Car()
                {
                    Id = 3, CarMark = "Audi", CarModel = "A4", CarEngine = 2
                }
            };

            using (var trans = context.Database.BeginTransaction())
            {
                foreach (var section in sections)
                {
                    context.Cars.Add(section);
                }

                context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cars] ON");
                context.SaveChanges();
                context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cars] OFF");
                trans.Commit();
            }
        }
Ejemplo n.º 29
0
        public static void Main(string[] args)
        {
            var db = new CarDbContext();

            using (db)
            {
                db.Database.Migrate();

                // AddMakesToDb(db);

                // AddModelsToOpel(db);

                // AddCarsToInsignia(db);

                // AddCarToCustomer(db);

                // AddAddressToCustomer(db);

                // GetPurchase(db);

                db.SaveChanges();
            }
        }
Ejemplo n.º 30
0
        public static void Initialize(CarDbContext context)
        {
            context.Database.EnsureCreated();

            // Look for any students.
            if (context.Cars.Any())
            {
                return;   // DB has been seeded
            }

            var cars = new[]
            {
                new Car {
                    Make = "BMW", Model = "740", Year = 1999, HorsePowerCount = 400
                },

                new Car {
                    Make = "Mercedes-benz", Model = "S500", Year = 1994, HorsePowerCount = 355
                },

                new Car {
                    Make = "Bugatti", Model = "Veyron", Year = 2018, HorsePowerCount = 700
                },

                new Car {
                    Make = "Toyota", Model = "Corolla", Year = 2021, HorsePowerCount = 155
                }
            };

            foreach (var car in cars)
            {
                context.Cars.Add(car);
            }

            context.SaveChanges();
        }