Exemplo n.º 1
0
        public async Task AddCar(CarData car)
        {
            await using var db = new CarsContext();
            await db.Cars.AddAsync(car);

            await db.SaveChangesAsync();
        }
Exemplo n.º 2
0
 public Car Get(Expression <Func <Car, bool> > filter)
 {
     using (CarsContext context = new CarsContext())
     {
         return(context.Set <Car>().SingleOrDefault(filter));
     }
 }
Exemplo n.º 3
0
        public BuildVehicleVM(Frame main, MainWindow window, BuildVehiclePage buildVehiclePage)
        {
            this.buildVehiclePage = buildVehiclePage;
            this.window           = window;
            this.main             = main;
            db = new CarsContext();

            Engines       = new ObservableCollection <Engine>(db.Engine.ToList());
            Colors        = new ObservableCollection <Models.Color>(db.Color.ToList());
            Headlights    = new ObservableCollection <Option>(db.Option.ToList());
            Wheels        = new ObservableCollection <Option>();
            Mirrors       = new ObservableCollection <Option>();
            Wings         = new ObservableCollection <Option>();
            Seats         = new ObservableCollection <Option>();
            Upholsteries  = new ObservableCollection <Option>();
            Steerings     = new ObservableCollection <Option>();
            Heatings      = new ObservableCollection <Option>();
            Sills         = new ObservableCollection <Option>();
            Lightings     = new ObservableCollection <Option>();
            Others        = new ObservableCollection <OptionModel>();
            Models        = new ObservableCollection <Model>(db.Model.ToList());
            Brands        = new ObservableCollection <Brand>(db.Brand.ToList());
            SelectedBrand = Brands.First();
            SelectedModel = Models.First();
        }
Exemplo n.º 4
0
        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();
            }
        }
Exemplo n.º 5
0
        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();
            }
        }
 public CarImpactClassesController(
     CarsContext context,
     IMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
Exemplo n.º 7
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();
     }
 }
Exemplo n.º 8
0
 public CarProbabilityClassesController(
     CarsContext context,
     IMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
Exemplo n.º 9
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.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            // добавляем поддержку сессий
            app.UseSession();

            // добавляем компонента miidleware по инициализации базы данных
            app.UseDbInitializer();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 10
0
        public StaticticVM()
        {
            db            = new CarsContext();
            baseDate1     = new DateTime(2019, 12, 20);
            baseDate2     = DateTime.Now;
            selectedDate1 = baseDate1;
            selectedDate2 = baseDate2;
            allContracts  = new ObservableCollection <ContractModel>(db.Contract.ToList()
                                                                     .Where(i => i.Type == "Покупка")
                                                                     .Select(i => new ContractModel()
            {
                contract   = i,
                model      = i.Vehicle.Kit.Model.Name,
                modelId    = i.Vehicle.Kit.Model.Id,
                kit        = i.Vehicle.Kit.Name,
                client     = i.Client.Name,
                employee   = i.Employee.Name,
                employeeId = i.Employee.Id,
                date       = i.Date.ToString("dd.MM.yyyy")
            }));
            selectedContracts = new ObservableCollection <ContractModel>();
            allContracts.ToList().ForEach(i => selectedContracts.Add(i));

            int s = 0;

            foreach (var item in selectedContracts)
            {
                s += (int)(item.contract.Total_Price);
            }
            Sum = s.ToString();

            Models    = new ObservableCollection <Model>(db.Model.ToList());
            Employees = new ObservableCollection <Employee>(db.Employee.ToList());
        }
Exemplo n.º 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));
                }
        }
Exemplo n.º 12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseSession();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapHub <ChatHub>("/chatHub");
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default",
                                template: "{controller=Home}/{action=Index}/{id?}");
            });

            using (var scope = app.ApplicationServices.CreateScope())
            {
                CarsContext context = scope.ServiceProvider.GetRequiredService <CarsContext>();
                DBObjects.First(context);
            }
        }
Exemplo n.º 13
0
 public void RunSeedMethod_WithoutDescription()
 {
     using (var ctx = new CarsContext())
     {
         ctx.Seed <CarBodyStyle>(descriptionField: null);
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Загрузка
        /// </summary>
        public static ObservableCollection <Auto> Load()
        {
            using (CarsContext db = new CarsContext())
            {
                var cars       = db.Cars;
                var services   = db.Services;
                var refuelings = db.Refuelings;
                var spareParts = db.SpareParts;
                foreach (var item in cars)
                {
                    foreach (var service in services)
                    {
                    }
                    foreach (var refueling in refuelings)
                    {
                    }
                    foreach (var sparePart in spareParts)
                    {
                    }
                    Cars.Add(item);
                }

                return(Cars);
            }
        }
Exemplo n.º 15
0
 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);
     }
 }
Exemplo n.º 16
0
        public void UpdateFirstCar()
        {
            int carId = 4;

            using (var ts = new TransactionScope())
            {
                using (var uow = new UnitOfWorkScope <CarsContext>(UnitOfWorkScopePurpose.Writing))
                {
                    Car c = SharedQueries.GetCar(carId);
                    c.Color = "White";
                    uow.SaveChanges();
                }

                using (var ctx = new CarsContext())
                {
                    Assert.AreEqual("White",
                                    ctx.Cars.Single(c => c.CarId == carId).Color);
                }
            }

            using (var ctx = new CarsContext())
            {
                Assert.AreEqual("Red",
                                ctx.Cars.Single(c => c.CarId == carId).Color);
            }
        }
Exemplo n.º 17
0
 public void CreateWorks()
 {
     using (var context = new CarsContext())
     {
         var make = context.Makes.FirstOrDefault();
         Assert.IsNull(make);
     }
 }
 public DisplayCarModel GetCar(long carId)
 {
     using (var dbContext = new CarsContext())
     {
         var carInstance = dbContext.GetCar.SqlQuery("EXECUTE GetCar {0}", carId).ToListAsync().Result.FirstOrDefault();
         return(carInstance);
     }
 }
 public List <DisplayCarModelModel> GetCarBrandModels(long carBrandId)
 {
     using (var dbContext = new CarsContext())
     {
         var carBrandModelsList = dbContext.GetCarBrandModels.SqlQuery("EXECUTE GetCarBrandModels {0}", carBrandId).ToListAsync().Result;
         return(carBrandModelsList);
     }
 }
 public List <DisplayCarBrandModel> GetCarBrands()
 {
     using (var dbContext = new CarsContext())
     {
         var carBrandsList = dbContext.GetCarBrand.SqlQuery("EXECUTE GetCarBrands").ToListAsync().Result;
         return(carBrandsList);
     }
 }
Exemplo n.º 21
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();
     }
 }
Exemplo n.º 22
0
        public static void Seed()
        {
            using (var context = new CarsContext())
            {
                new Configuration().Seed(context);

                context.SaveChanges();
            }
        }
Exemplo n.º 23
0
 public ContractVM(AppViewModel vm, VehicleModel v)
 {
     db           = new CarsContext();
     contractType = "покупку";
     appViewModel = vm;
     vehicle      = v;
     employee     = vm.Window.Employee;
     date         = DateTime.Now;
 }
Exemplo n.º 24
0
        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));
        }
Exemplo n.º 25
0
 public ContractVM(BuildVehicleVM vm, VehicleModel v)
 {
     db             = new CarsContext();
     contractType   = "заказ";
     buildVehicleVM = vm;
     vehicle        = v;
     employee       = vm.Window.Employee;
     date           = DateTime.Now;
 }
Exemplo n.º 26
0
 public ReportService(
     CarsContext context,
     IMapper mapper,
     IAppLogger <ReportService> logger)
 {
     _context = context ?? throw new ArgumentNullException(nameof(context));
     _mapper  = mapper ?? throw new ArgumentNullException(nameof(mapper));
     _logger  = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            using (CarsContext context = new CarsContext())
            {
                Console.WriteLine(context.Cars.Count(x => x.Manufacturer.Name == "BMW"));
            }
        }
Exemplo n.º 28
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();
     }
 }
Exemplo n.º 29
0
 public List <Car> GetAll(Expression <Func <Car, bool> > filter = null)
 {
     using (CarsContext context = new CarsContext())
     {
         return(filter == null
             ? context.Set <Car>().ToList()
             : context.Set <Car>().Where(filter).ToList());
     }
 }
Exemplo n.º 30
0
 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();
     }
 }
Exemplo n.º 31
0
 public void Add(Car car)
 {
     //_car.Add(car);
     using (CarsContext context = new CarsContext())
     {
         var addedEntity = context.Entry(car);
         addedEntity.State = EntityState.Added;
         context.SaveChanges();
     }
 }
        public static CarReadModel GetById3(int id)
        {
            using (CarsContext ctx = new CarsContext())
            {
                return (
from c in ctx.Cars.SelectCarReadModel()
where c.Car.CarId == id
select c
                ).Single();
            }
        }
        public static CarReadModel SearchByBrand(string brandFilter)
        {
            using (CarsContext ctx = new CarsContext())
            {
                return (
from c in ctx.Cars.SelectCarReadModel()
where c.BrandName.StartsWith(brandFilter)
select c
                ).Single();
            }   
        }
        public static CarReadModel GetById(int id)
        {
            using (CarsContext ctx = new CarsContext())
            {
                return (
from c in ctx.Cars
where c.CarId == id
select new CarReadModel
{
    Car = c,
    BrandName = c.Brand.Name
}
                    ).Single();
            }
        }
Exemplo n.º 35
0
 public PluginConfig(CarsContext carsContext,
     IWorkContext workContext)
 {
     _carsContext = carsContext;
     _workContext = workContext;
 }