コード例 #1
0
 public Car Post([FromBody] Car value)
 {
     if (ModelState.IsValid)
     {
         _context.Add(value);
         _context.SaveChanges();
         return(_context.Cars.Find(value.Id));
     }
     return(null);
 }
コード例 #2
0
        public ActionResult Create([Bind(Include = "Id,Name,State,City")] Owner owner)
        {
            if (ModelState.IsValid)
            {
                db.Owners.Add(owner);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(owner));
        }
コード例 #3
0
        public ActionResult Create([Bind(Include = "PointId,Name")] Point point)
        {
            if (ModelState.IsValid)
            {
                db.Points.Add(point);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(point));
        }
コード例 #4
0
        public ActionResult Create([Bind(Include = "Id,OwnerId,Vin,Model,Make,Year")] Vehicle vehicle)
        {
            if (ModelState.IsValid)
            {
                db.Vehicles.Add(vehicle);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(vehicle));
        }
コード例 #5
0
        public ActionResult Create([Bind(Include = "CarTypeId,Name")] CarType carType)
        {
            if (ModelState.IsValid)
            {
                db.CarTypes.Add(carType);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(carType));
        }
コード例 #6
0
ファイル: CarsController.cs プロジェクト: skyrr/CarAppDBFirst
        public ActionResult Create([Bind(Include = "CarId,Name,CarTypeId,Consumption")] Car car)
        {
            if (ModelState.IsValid)
            {
                db.Cars.Add(car);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CarTypeId = new SelectList(db.CarTypes, "CarTypeId", "Name", car.CarTypeId);
            return(View(car));
        }
コード例 #7
0
        public ActionResult Create(Car car)
        {
            if (ModelState.IsValid)
            {
                db.Cars.Add(car);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.BrandId = new SelectList(db.Brands, "BrandId", "Name", car.BrandId);
            return(View(car));
        }
コード例 #8
0
        public CarModel AddCar(CarModel carModel)
        {
            if (_context.Cars.Any(x => x.Id == carModel.Id))
            {
                throw new Exception("A car already exists for this ID");
            }
            var newCar = _mapper.Map <Database.Entities.Car>(carModel);

            _context.Cars.Add(newCar);
            _context.SaveChanges();
            return(_mapper.Map <CarModel>(newCar));
        }
コード例 #9
0
        public ActionResult Create([Bind(Include = "TravelId,Name,DirectionId,CarId,TravelDate")] Travel travel)
        {
            if (ModelState.IsValid)
            {
                db.Travels.Add(travel);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CarId       = new SelectList(db.Cars, "CarId", "Name", travel.CarId);
            ViewBag.DirectionId = new SelectList(db.Directions, "DirectionId", "Name", travel.DirectionId);
            return(View(travel));
        }
コード例 #10
0
        public ActionResult Create([Bind(Include = "DirectionId,Name,DepartureId,DestinationId,Distance")] Direction direction)
        {
            if (ModelState.IsValid)
            {
                db.Directions.Add(direction);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.DepartureId   = new SelectList(db.Points, "PointId", "Name", direction.DepartureId);
            ViewBag.DestinationId = new SelectList(db.Points, "PointId", "Name", direction.DestinationId);
            return(View(direction));
        }
コード例 #11
0
        //[ExpectedException(typeof(InvalidOperationException))]
        public void TestNavigationAndForeignKeyConflictingChanges()
        {
            using (TransactionScope ts = new TransactionScope())
                using (CarsContext context = new CarsContext())
                {
                    var brands = context.Brands.Include(b => b.Cars).OrderBy(b => b.BrandId);
                    var car    = brands.First().Cars.First();

                    Debug.WriteLine("The car has BrandId {0} pointing to Brand \"{1}\"",
                                    car.BrandId, car.Brand.Name);
                    Brand newBrand   = brands.Skip(1).First();
                    int   newBrandId = brands.Skip(2).First().BrandId;

                    Debug.WriteLine(string.Format("Setting Brand to {0}", newBrand.Name));
                    car.Brand = newBrand;
                    Debug.WriteLine(string.Format("The car has BrandId {0} pointing to Brand \"{1}\"",
                                                  car.BrandId, car.Brand.Name));

                    Debug.WriteLine(string.Format("Setting BrandId to {0}", newBrandId));
                    car.BrandId = newBrandId;
                    Debug.WriteLine(string.Format("The car has BrandId {0} pointing to Brand \"{1}\"",
                                                  car.BrandId, car.Brand.Name));

                    Debug.WriteLine("Saving Changes...");
                    context.SaveChanges();
                    Debug.WriteLine(string.Format("The car has BrandId {0} pointing to Brand \"{1}\"",
                                                  car.BrandId, car.Brand.Name));
                }
        }
コード例 #12
0
ファイル: CarsController.cs プロジェクト: Sar1n/TaxiPark
 public HttpResponseMessage Put([FromBody] CarPutDTO car)
 {
     try
     {
         CarsContext db         = new CarsContext();
         int         idtochange = int.Parse(car.Id);
         var         actualcar  = from c in db.Cars
                                  where c.Id == idtochange
                                  select c;
         if (actualcar.First() != null)
         {
             actualcar.First().LicenseNumber = car.Licence;
             actualcar.First().Mileage       = int.Parse(car.Mileage);
             var newcarmodel = from m in db.Models
                               where m.Model.ToLower() == car.Model.ToLower()
                               select m;
             actualcar.First().Model = newcarmodel.First();
             db.SaveChanges();
             HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
             return(response);
         }
         else
         {
             throw new Exception();
         }
     }
     catch (Exception)
     {
         HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError);
         return(response);
     }
 }
コード例 #13
0
ファイル: Program.cs プロジェクト: senaitesfazgi/4.1EF
        static void Main(string[] args)
        {
            //Initialize our database interaction

            /*
             * using (CarsContext context = new CarsContext())
             * {
             *   string make, model, colour;
             *   Console.WriteLine(context.Cars.Count(x => x.Manufacturer.Name == "BMW"));
             *   Console.WriteLine(context.Cars.Count(x => x.Manufacturer.Name == "Mercedes-Benz"));
             *   Console.Write("Please enter a make for your new Car:");
             *   make = Console.ReadLine();
             *   Console.Write("Please enter a model for your new Car:");
             *   model = Console.ReadLine();
             *   Console.Write("Please enter a colour for your new Car:");
             *   colour = Console.ReadLine();
             *   context.Add(new Car()
             *   {
             *       Manufacturer = context.Manufacturers.Where(x => x.Name == make).SingleOrDefault(),
             *       Model = model,
             *       Colour = colour
             *   });
             *   context.SaveChanges();
             * }*/
            using (CarsContext context = new CarsContext())
            {
                string model;
                Console.Write("Please enter a model to remove: ");
                model = Console.ReadLine();

                context.Cars.Remove(context.Cars.Where(x => x.Model == model).SingleOrDefault());

                context.SaveChanges();
            }
        }
コード例 #14
0
 public CarsAPIController(CarsContext context)
 {
     db = context;
     if (!db.Cars.Any())
     {
         db.Cars.Add(new Car {
             CarBrand = "DeLorean", CarModel = "DMC-12", CarNum = "OUTATIME", CarColor = "Silver", CarPruductionYear = "1981", CarOwnerFirstName = "Марти", CarOwnerLastName = "Макфлай",
         });
         db.Cars.Add(new Car {
             CarBrand = "Aston Martin", CarModel = "DB5", CarNum = "BMT 216A", CarColor = "Silver", CarPruductionYear = "1970", CarOwnerFirstName = "Джеймс", CarOwnerLastName = "Бонд",
         });
         db.Cars.Add(new Car {
             CarBrand = "Chevrolet", CarModel = "Sport 108", CarNum = "Отсутствуют", CarColor = "Sea", CarPruductionYear = "1968", CarOwnerFirstName = "Фред", CarOwnerLastName = "Джонс",
         });
         db.Cars.Add(new Car {
             CarBrand = "British Leyland", CarModel = "Mini 1000", CarNum = "SLW 287R", CarColor = "Yellow", CarPruductionYear = "1976", CarOwnerFirstName = "Mr.", CarOwnerLastName = "Bean",
         });
         db.Cars.Add(new Car {
             CarBrand = "Peugeot", CarModel = "406", CarNum = "724NLB13", CarColor = "White", CarPruductionYear = "1995", CarOwnerFirstName = "Даниэль", CarOwnerLastName = "Моралес",
         });
         db.Cars.Add(new Car {
             CarBrand = "Audi", CarModel = "A8", CarNum = "247 BRD 06", CarColor = "Black", CarPruductionYear = "2006", CarOwnerFirstName = "Tom", CarOwnerLastName = "Tom",
         });
         db.SaveChanges();
     }
 }
コード例 #15
0
ファイル: Program.cs プロジェクト: Danielle-Nicholson/4.1-EF
        static void Main(string[] args)
        {
            // Step 1: Install dotnet-ef if it isn't:
            // dotnet tool install --global dotnet-ef

            // Step 2: Install the packages in the project:
            // dotnet add package Microsoft.EntityFrameworkCore.Design
            // dotnet add package Pomelo.EntityFrameworkCore.MySql

            // Step 3: Create the models and context:
            // dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=;database=DB_NAME" Pomelo.EntityFrameworkCore.MySql -c CONTEXT_NAME -o Models -f -d

            // Step 4: Pluralize the property names in the context file.

            // Step 5: Pluralize the virtual ICollections in the table classes (and their InverseProperty's).

            // Step 6 (optional): Rename any instances of "Id" to "ID".

            // Initialize our database interaction (the context):
            using (CarsContext context = new CarsContext())
            {
                string model;
                Console.Write("Please enter a model to remove: ");
                model = Console.ReadLine();

                context.Cars.Remove(context.Cars.Where(x => x.Model == model).SingleOrDefault());

                context.SaveChanges();
            }
        }
コード例 #16
0
 /// <summary>
 /// Сохранение
 /// </summary>
 public static void Save <T>(T item) where T : class
 {
     using (CarsContext db = new CarsContext())
     {
         db.Set <T>().Add(item);
         db.SaveChanges();
     }
 }
コード例 #17
0
ファイル: CarsController.cs プロジェクト: Sar1n/TaxiPark
        public HttpResponseMessage Delete(int id)
        {
            CarsContext db          = new CarsContext();
            Cars        CarToDelete = db.Cars.Find(id);

            db.Cars.Remove(CarToDelete);
            db.SaveChanges();
            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
コード例 #18
0
 public static void Insert <TEntity>(List <TEntity> entity) where TEntity : class
 {
     using (CarsContext context = new CarsContext())
     {
         DbSet <TEntity> dbset = context.Set <TEntity>();
         dbset.AddRange(entity);
         context.SaveChanges();
     }
 }
コード例 #19
0
        public static void Seed()
        {
            using (var context = new CarsContext())
            {
                new Configuration().Seed(context);

                context.SaveChanges();
            }
        }
コード例 #20
0
 public static void Update <TEntity>(TEntity entity) where TEntity : class
 {
     using (CarsContext context = new CarsContext())
     {
         DbSet <TEntity> dbset = context.Set <TEntity>();
         context.Entry(entity).State = EntityState.Modified;
         context.Database.Log        = Console.WriteLine;
         context.SaveChanges();
     }
 }
コード例 #21
0
ファイル: ShopCart.cs プロジェクト: Muhamedzhan/OnlineShop
        public void AddToCart(Car car)
        {
            carsContext.ShopCartItem.Add(new ShopCartItem {
                ShopCartId = ShopCartId,
                car        = car,
                price      = car.price
            });

            carsContext.SaveChanges();
        }
コード例 #22
0
ファイル: CarDal.cs プロジェクト: DzhanHalim/ReCapCarProject
 public void Delete(Car car)
 {
     //_car.Remove(_car.FirstOrDefault(x => x.Id == car.Id));
     using (CarsContext context = new CarsContext())
     {
         var deletedEntity = context.Entry(car);
         deletedEntity.State = EntityState.Deleted;
         context.SaveChanges();
     }
 }
コード例 #23
0
ファイル: CarDal.cs プロジェクト: DzhanHalim/ReCapCarProject
 public void Add(Car car)
 {
     //_car.Add(car);
     using (CarsContext context = new CarsContext())
     {
         var addedEntity = context.Entry(car);
         addedEntity.State = EntityState.Added;
         context.SaveChanges();
     }
 }
コード例 #24
0
 public void TestStoreBrand()
 {
     using (TransactionScope ts = new TransactionScope())
         using (CarsContext context = new CarsContext())
         {
             Brand volvo = new Brand {
                 Name = "Volvo"
             };
             context.Brands.Add(volvo);
             context.SaveChanges();
         }
 }
コード例 #25
0
ファイル: CarsController.cs プロジェクト: kyweez/CDA_2005
        public IActionResult Create(Car car)
        {
            if (ModelState.IsValid)
            {
                ctx.Cars.Add(car);

                ctx.SaveChanges();

                return(RedirectToAction("Index"));
            }

            return(View(car));
        }
コード例 #26
0
        static void Main(string[] args)
        {
            using (CarsContext context = new CarsContext())
            {
                string model;
                Console.Write("Please enter a model to remove: ");
                model = Console.ReadLine();

                context.Cars.Remove(context.Cars.Where(x => x.Model == model).SingleOrDefault());

                context.SaveChanges();
            }
        }
コード例 #27
0
        public void TestChangeTrackingSimpleType()
        {
            using (TransactionScope ts = new TransactionScope())
                using (CarsContext context = new CarsContext())
                {
                    var phoneBook = context.PhoneBook.ToList();
                    var entry     = phoneBook.First();

                    entry.PhoneNumber = "4567";

                    Debug.WriteLine("Saving changes...");
                    context.SaveChanges();
                }
        }
コード例 #28
0
        public void TestSavingChanges()
        {
            using (var ctx = new CarsContext())
            {
                var objCtx = ((IObjectContextAdapter)ctx).ObjectContext;

                bool eventCalled = false;

                objCtx.SavingChanges += (sender, args) => eventCalled = true;

                ctx.SaveChanges();

                Assert.IsTrue(eventCalled);
            }
        }
コード例 #29
0
ファイル: CarDal.cs プロジェクト: DzhanHalim/ReCapCarProject
        public void Update(Car car)
        {
            //Car carToUpdate = _car.FirstOrDefault(x => x.Id == car.Id);
            //carToUpdate.ModelYear = car.ModelYear;
            //carToUpdate.Price = car.ModelYear;
            //carToUpdate.Description = car.Description;
            //carToUpdate.ColorId = car.ColorId;
            //carToUpdate.BrandId = car.BrandId;

            using (CarsContext context = new CarsContext())
            {
                var updatedEntity = context.Entry(car);
                updatedEntity.State = EntityState.Modified;
                context.SaveChanges();
            }
        }
コード例 #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, CarsContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());

            app.UseMvc();


            if (!context.Cars.Any())
            {
                context.Cars.AddRange(new List <Cars>()
                {
                    new Cars()
                    {
                        Model = "Focus", Description = "sedan", Year = 2010, Brand = "Ford", Kilometers = 80000, Price = 135200
                    },
                    new Cars()
                    {
                        Model = "Gol", Description = "Hatchbak", Year = 2012, Brand = "VW", Kilometers = 85000, Price = 115350
                    },
                    new Cars()
                    {
                        Model = "Jetta", Description = "sedan", Year = 2015, Brand = "VW", Kilometers = 70000, Price = 175000
                    },
                    new Cars()
                    {
                        Model = "Mazda 3", Description = "Hatchbak", Year = 2012, Brand = "Mazda", Kilometers = 78000, Price = 145000
                    },
                    new Cars()
                    {
                        Model = "Camaro", Description = "sedan", Year = 2011, Brand = "Chevrolet", Kilometers = 60000, Price = 195500
                    }
                });

                context.SaveChanges();
            }
        }