public ActionResult Cars_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable <CarViewModel> cars)
        {
            var results = new List <CarViewModel>();

            foreach (var car in cars)
            {
                if (car != null && ModelState.IsValid)
                {
                    var newCar = new Car {
                        Name = car.Name
                    };
                    var category = db.Categories.Where(cat => cat.Name == car.Category).SingleOrDefault();
                    if (category == null)
                    {
                        category = new Category {
                            Name = car.Category
                        };
                    }
                    newCar.Category = category;
                    db.Cars.Add(newCar);
                    db.SaveChanges();
                    car.Id = newCar.Id;
                    results.Add(car);
                }
            }
            return(Json(results.ToDataSourceResult(request, ModelState)));
        }
Example #2
0
 protected override void Seed(CarsDbContext context)
 {
     this.SeedOwners(context);
     context.SaveChanges();
     this.SeedCarModels(context);
     context.SaveChanges();
     this.SeedCars(context);
     context.SaveChanges();
 }
        public void Post([FromBody] Car car)
        {
            //if (!ModelState.IsValid)
            //{

            //}
            context.Cars.Add(car);
            context.SaveChanges();
        }
Example #4
0
 public IActionResult CreatePost()
 {
     if (!ModelState.IsValid)
     {
         return(View(ModelVM));
     }
     _db.Models.Add(ModelVM.Model);
     _db.SaveChanges();
     return(RedirectToAction(nameof(Index)));
 }
Example #5
0
        public ActionResult CreateCar([FromBody] Car Car)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            dbContext.Car.Add(Car);
            dbContext.SaveChanges();
            return(Created("api/Cars", Car));
        }
        public ActionResult Create([Bind(Include = "ID,Year,Make,Model,Color,Engine")] Cars cars)
        {
            if (ModelState.IsValid)
            {
                db.Autos.Add(cars);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(cars));
        }
Example #7
0
        public IActionResult Create(Make make)
        {
            if (ModelState.IsValid)
            {
                _db.Add(make);
                _db.SaveChanges();
                return(RedirectToAction(nameof(Index)));
            }

            return(View(make));
        }
        public ActionResult Create([Bind(Include = "ID,CarName,IsChecked")] Cars cars)
        {
            if (ModelState.IsValid)
            {
                db.Cars.Add(cars);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(cars));
        }
Example #9
0
        public IHttpActionResult AddCar([FromBody] Car car)
        {
            if (ModelState.IsValid)
            {
                dbContext.Cars.Add(car);
                dbContext.SaveChanges();

                return(Ok(car));
            }
            else
            {
                return(BadRequest());
            }
        }
 public async Task <bool> AddItemAsync(Car model)
 {
     using var dbCtx = new CarsDbContext();
     dbCtx.Cars.Add(model);
     dbCtx.SaveChanges();
     return(await Task.FromResult(true));
 }
Example #11
0
        public ActionResult Create(CreateCarModel carModel)
        {
            if (carModel != null && ModelState.IsValid)
            {
                var ownerId = this.User.Identity.GetUserId();

                var car = new Car
                {
                    Make        = carModel.Make,
                    Model       = carModel.Model,
                    Color       = carModel.Color,
                    Engine      = carModel.Engine,
                    EngineType  = carModel.EngineType,
                    ImageUrl    = carModel.ImageUrl,
                    Power       = carModel.Power,
                    PricePerDay = carModel.PricePerDay,
                    Year        = carModel.Year,
                    OwnerId     = ownerId
                };

                var db = new CarsDbContext();

                db.Cars.Add(car);
                db.SaveChanges();

                return(RedirectToAction("Details", new { id = car.Id }));
            }

            return(View());
        }
Example #12
0
        public static void Import(CarsDbContext data)
        {
            data.Configuration.AutoDetectChangesEnabled = false;
            data.Configuration.ValidateOnSaveEnabled    = false;

            var files = Directory.GetFiles(JsonFolder).Select(x => x).Where(x => Path.GetExtension(x) == ".json").ToList();

            Console.WriteLine("Importing json data into SQL");

            var cars = files.Select(f => File.ReadAllText(f))
                       .SelectMany(json => JsonConvert.DeserializeObject <IEnumerable <CarJson> >(json))
                       .ToList();

            var citiesHash = new HashSet <string>();
            var manuHash   = new HashSet <string>();

            foreach (var car in cars)
            {
                var city = car.Dealer.City;
                var manu = car.ManufacturerName;

                if (!citiesHash.Contains(city))
                {
                    citiesHash.Add(city);
                }

                if (!manuHash.Contains(manu))
                {
                    manuHash.Add(manu);
                }
            }

            data.SaveChanges();
        }
Example #13
0
        public static void PopulateFromJsonFile(CarsDbContext context, string jsonFileName)
        {
            StreamReader   reader         = new StreamReader(jsonFileName);
            JsonTextReader jsonReader     = new JsonTextReader(reader);
            JsonSerializer jsonSerializer = new JsonSerializer();
            var            parsedData     = jsonSerializer.Deserialize(jsonReader).ToString();
            var            carsArray      = JArray.Parse(parsedData);

            foreach (var car in carsArray)
            {
                var newCar = new Car();
                newCar.Year             = int.Parse((string)car["Year"]);
                newCar.TransmissionType = ((TransmissionTypes)(int.Parse((string)car["TransmissionType"]))).ToString();
                newCar.Manufacturer     = GetManufacturerByName(context, (string)car["ManufacturerName"]);
                newCar.Model            = (string)car["Model"];
                newCar.Price            = decimal.Parse((string)car["Price"]);
                var dealer = new Dealer()
                {
                    Name = (string)car["Dealer"]["Name"]
                };
                dealer.Cities.Add(GetCityByName(context, (string)car["Dealer"]["City"]));
                newCar.Dealer = dealer;

                context.Cars.Add(newCar);
                context.SaveChanges();
            }
        }
Example #14
0
        public ActionResult Rent(int carId, int days)
        {
            var db = new CarsDbContext();

            var car = db.Cars
                      .Where(c => c.Id == carId)
                      .FirstOrDefault();

            var userId = this.User.Identity.GetUserId();

            if (car == null || car.IsRented || car.OwnerId == userId)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var renting = new Renting
            {
                CarId      = carId,
                Days       = days,
                RentedOn   = DateTime.Now,
                UserId     = userId,
                TotalPrice = days * car.PricePerDay
            };

            car.IsRented = true;

            db.Rentings.Add(renting);
            db.SaveChanges();

            return(RedirectToAction("Details", new { id = car.Id }));
        }
        public Car Create(string brand, string modelName, int year)
        {
            Car car = new Car(brand, modelName, year);

            _carsDbContext.CarList.Add(car);

            _carsDbContext.SaveChanges();

            return(car);
        }
        public void When_a_car_is_saved_in_the_database_it_should_succeed()
        {
            CarsDbContext context = new CarsDbContext(base.ConnectionString);

            context.Cars.Add(new Car()
            {
                Make  = "make",
                Model = "model",
            });
            context.SaveChanges();
        }
 public async Task <bool> DeleteItemAsync(string id)
 {
     if (!Int32.TryParse(id, out int Id))
     {
         return(false);
     }
     using var dbCtx = new CarsDbContext();
     _ = dbCtx.Cars.Remove(dbCtx.Cars.SingleOrDefault(e => e.Id == Id));
     dbCtx.SaveChanges();
     return(await Task.FromResult(true));
 }
Example #18
0
        public void CreateCar(Car model)
        {
            var car = new Car
            {
                Make           = model.Make,
                Model          = model.Model,
                MakeId         = model.MakeId,
                ModelId        = model.ModelId,
                Category       = model.Category,
                Description    = model.Description,
                HorsePower     = model.HorsePower,
                Image          = model.Image,
                Price          = model.Price,
                TypeOfEngine   = model.TypeOfEngine,
                TypeOfGearbox  = model.TypeOfGearbox,
                YearOfBuilding = model.YearOfBuilding
            };

            db.Cars.Add(car);

            db.SaveChanges();
        }
Example #19
0
        private static void InsertData()
        {
            var cars = ProcessCar("/Users/javiermayorga/Documents/Dev/LINQFundamentalsC-sharp/LinqAndEntityFramework/src/LINQAndEntityFrameworkExample/context/fuel.csv");
            var db   = new CarsDbContext();

            db.Database.EnsureCreated();

            if (!db.Cars.Any())
            {
                foreach (var car in cars)
                {
                    db.Add(car);
                }
                db.SaveChanges();
            }
        }
Example #20
0
        public ActionResult ConfirmDelete(int id)
        {
            using (var db = new CarsDbContext())
            {
                Car car = db.Cars.Find(id);

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

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

                return(RedirectToAction("All"));
            }
        }
        public async Task <bool> UpdateItemAsync(Car model)
        {
            if (model == null)
            {
                return(await Task.FromResult(false));
            }
            using var dbCtx = new CarsDbContext();
            var dbModel = dbCtx.Cars.SingleOrDefault(e => e.Id == model.Id);

            if (dbModel != null)
            {
                dbModel.Brand = model.Brand;
                dbModel.Model = model.Model;
                dbModel.Owner = model.Owner;
                dbCtx.SaveChanges();
            }
            return(await Task.FromResult(true));
        }
Example #22
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            var context = new CarsDbContext();
            //ResetDatabase(context);

            var cars = context
                       .Cars
                       .Include(c => c.Engine)
                       .Include(c => c.Make)
                       .Include(c => c.LicensePlate)
                       .Include(c => c.CarDealerships)
                       .ThenInclude(cd => cd.Dealership)
                       .OrderBy(c => c.ProductionYear)
                       .ToArray();


            context.SaveChanges();



            foreach (var car in cars)
            {
                Console.WriteLine($"{car.Make.Name} {car.Model}");


                Console.WriteLine($"--Dealership:");

                foreach (var carDealership in car.CarDealerships)
                {
                    var dealership = carDealership.Dealership;
                    Console.WriteLine("----" + dealership.Name);
                }

                Console.WriteLine($"--Fuel: {car.Engine.FuelType}");
                Console.WriteLine($"--Transmission: {car.Transmission}");
                var licensePlate = car.LicensePlate != null ? $"--{car.LicensePlate.Number}" : "No Plate";
                Console.WriteLine($"--Plate number: {licensePlate}");
                Console.WriteLine("---------------------------");
            }


            Console.WriteLine();
        }
 public async Task <ActionResult <IEnumerable <CarsForSale> > > GetcarsForSales()
 {
     if (_context.carsForSales.Count() == 0)
     {
         _context.carsForSales.AddRange(new List <CarsForSale> {
             new CarsForSale {
                 Brand = "Chevrolet", Model = "Corvette", Price = 100000.1M, Year = 2010, Description = "Bonito Chevrolet Corvette de 6ta generacion", PhotoUrl = IMAGE_URL
             },
             new CarsForSale {
                 Brand = "Chrysler", Model = "200", Year = 2015, Price = 120000, Description = "Flamante  200 unico dueño", PhotoUrl = IMAGE_URL
             },
             new CarsForSale {
                 Brand = "Ford", Model = "Mustang", Year = 2018, Price = 220000, Description = "Mustang v6 en excelente estado, 40 mil km", PhotoUrl = IMAGE_URL
             }
         });
         _context.SaveChanges();
     }
     return(await _context.carsForSales.ToListAsync());
 }
Example #24
0
        private void SeedCarModels(CarsDbContext context)
        {
            var models = new List <CarModel>()
            {
                new CarModel()
                {
                    Id = 1, Description = "Model 1"
                },
                new CarModel()
                {
                    Id = 2, Description = "Model 2"
                }
            };

            foreach (var model in models)
            {
                context.CarModels.Add(model);
                context.SaveChanges();
            }
        }
Example #25
0
        static void Main(string[] args)
        {
            using (var db = new CarsDbContext())
            {
                //ResetDatabase(db);

                var plates = db.LicensePlates.ToArray();
                var cars   = db.Cars
                             .Include(c => c.Engine)
                             .Include(c => c.Make)
                             .Include(c => c.LicensePlate)
                             .Include(c => c.CarDealerships)
                             .ThenInclude(cd => cd.Dealership)
                             .OrderBy(c => c.ProductionYear)
                             .ToArray();

                cars[1].LicensePlate = plates.Single(p => p.LicensePlateId == 3);
                db.SaveChanges();

                foreach (var car in cars)
                {
                    Console.WriteLine($"{car.Make.Name}");
                    foreach (var carDealer in car.CarDealerships)
                    {
                        var dealership = carDealer.Dealership;
                        Console.WriteLine($"--{dealership.Name}");
                    }
                    Console.WriteLine($"---Fuel { car.Engine.FuelType}");
                    Console.WriteLine($"---Transmission: { car.Transmission}");

                    var licensePlateNum = car.LicensePlate != null ? car.LicensePlate.Name : "No Plate";
                    Console.WriteLine($"-----LicensePlate: {licensePlateNum}");
                    Console.WriteLine("-------------------");
                }

                Console.WriteLine();
            }
        }
Example #26
0
        public ActionResult Edit(CarViewModel carModel)
        {
            if (ModelState.IsValid)
            {
                using (var db = new CarsDbContext())
                {
                    var car = db.Cars.Find(carModel.Id);

                    car.Make        = carModel.Make;
                    car.Model       = carModel.Model;
                    car.Color       = carModel.Color;
                    car.Year        = carModel.Year;
                    car.Engine      = carModel.Engine;
                    car.PricePerDay = carModel.PricePerDay;

                    db.SaveChanges();
                }

                return(RedirectToAction("Details", new { id = carModel.Id }));
            }

            return(View(carModel));
        }
Example #27
0
        private static void ImportCarsInFile(string filePath)
        {
            var jsonArrayStr  = File.ReadAllText(filePath);
            var parsedObjects = JsonConvert.DeserializeObject <JsonItemPlaceholder[]>(jsonArrayStr);

            int importedCarsCount = 0;

            foreach (var obj in parsedObjects)
            {
                var newCar = ParseCar(obj);

                db.Cars.Add(newCar);
                importedCarsCount++;

                carsImported.Add(newCar);

                if (importedCarsCount % 200 == 0)
                {
                    db.SaveChanges();
                    Console.WriteLine("\nSent 200 to db\n");
                }
            }
        }
Example #28
0
        private void SeedOwners(CarsDbContext context)
        {
            var owners = new List <Owner>()
            {
                new Owner()
                {
                    Id = 1, FullName = "Pesho Peshov"
                },
                new Owner()
                {
                    Id = 2, FullName = "Gosho Goshov"
                },
                new Owner()
                {
                    Id = 3, FullName = "Tosho Toshov"
                }
            };

            foreach (var owner in owners)
            {
                context.Owners.Add(owner);
                context.SaveChanges();
            }
        }
Example #29
0
        private void SeedCars(CarsDbContext context)
        {
            var cars = new List <Car>()
            {
                new Car()
                {
                    Id = 1, OwnerId = 1, ModelId = 1, Description = "Car 1"
                },
                new Car()
                {
                    Id = 2, OwnerId = 3, ModelId = 1, Description = "Car 2"
                },
                new Car()
                {
                    Id = 3, OwnerId = 2, ModelId = 1, Description = "Car 3"
                },
                new Car()
                {
                    Id = 4, OwnerId = 1, ModelId = 2, Description = "Car 4"
                },
                new Car()
                {
                    Id = 5, OwnerId = 2, ModelId = 1, Description = "Car 5"
                },
                new Car()
                {
                    Id = 6, OwnerId = 1, ModelId = 2, Description = "Car 6"
                },
            };

            foreach (var car in cars)
            {
                context.Cars.Add(car);
                context.SaveChanges();
            }
        }
Example #30
0
        private static void Seed(CarsDbContext context)
        {
            var makes = new[]
            {
                new Make {
                    Name = "Ford"
                },
                new Make {
                    Name = "Mercedes"
                },
                new Make {
                    Name = "Audi"
                },
                new Make {
                    Name = "Bmw"
                },
                new Make {
                    Name = "АЗЛК"
                },
                new Make {
                    Name = "Лада"
                },
                new Make {
                    Name = "Трабант"
                },
            };

            context.Makes.AddRange(makes);

            var engines = new[]
            {
                new Engine {
                    Capacity = 1.6, Cyllinders = 4, FuelType = FuelType.Petrol, HorsePower = 95
                },

                new Engine {
                    Capacity = 3.0, Cyllinders = 8, FuelType = FuelType.Electric, HorsePower = 318
                },

                new Engine {
                    Capacity = 1.2, Cyllinders = 3, FuelType = FuelType.Gas, HorsePower = 60
                }
            };

            context.Engines.AddRange(engines);

            var licensePlates = new[]
            {
                new LicensePlate {
                    Number = "CB1234AN"
                },
                new LicensePlate {
                    Number = "CB4567BC"
                },
                new LicensePlate {
                    Number = "BP9999AA"
                },
            };

            context.LicensePlates.AddRange(licensePlates);

            var cars = new[]
            {
                new Car
                {
                    Engine         = engines[2],
                    Make           = makes[6],
                    Doors          = 4,
                    Model          = "Кашон-P50",
                    ProductionYear = new DateTime(1958, 1, 1),
                    Transmission   = Transmission.Manuel,
                    LicensePlate   = licensePlates[1]
                },

                new Car
                {
                    Engine         = engines[1],
                    Make           = makes[4],
                    Doors          = 3,
                    Model          = "Москвич-423",
                    ProductionYear = new DateTime(1954, 1, 1),
                    Transmission   = Transmission.Automatic
                },

                new Car
                {
                    Engine         = engines[0],
                    Make           = makes[0],
                    Doors          = 4,
                    Model          = "Escort",
                    ProductionYear = new DateTime(1955, 1, 1),
                    Transmission   = Transmission.Automatic,
                    LicensePlate   = licensePlates[2]
                }
            };

            context.Cars.AddRange(cars);

            var dealerships = new[]
            {
                new DealerShip {
                    Name = "SoftUni-Auto"
                },
                new DealerShip {
                    Name = "Fast and Furious Auto"
                }
            };

            context.DealerShips.AddRange(dealerships);

            var cardealerships = new[]
            {
                new CarDealerShip {
                    Car = cars[0], DealerShip = dealerships[0]
                },
                new CarDealerShip {
                    Car = cars[0], DealerShip = dealerships[1]
                },
                new CarDealerShip {
                    Car = cars[1], DealerShip = dealerships[1]
                },
            };

            context.CarDealerShips.AddRange(cardealerships);

            context.SaveChanges();
        }