예제 #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("FUN WITH EF CORE");

            using (var context = new AutoLotEntities())
            {
                MyDataInitializer.RecreateDatabase(context);
                MyDataInitializer.InitializeData(context);

                foreach (Inventory inv in context.Cars)
                {
                    Console.WriteLine(inv);
                }
            }

            Console.WriteLine("Fun with repos");

            using (var repo = new InventoryRepo())
            {
                foreach (var c in repo.GetAll())
                {
                    Console.WriteLine(c);
                }
            }

            Console.ReadLine();
        }
예제 #2
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);
            }
        }
예제 #3
0
        private static void Navigation()
        {
            ForegroundColor = ConsoleColor.Yellow;
            WriteLine("=> Navigation Properties");

            Write("-> Lazy loading:");
            int n = 0;

            using (var context = new AutoLotEntities())
                foreach (Car c in context.cars)
                {
                    Write($" {++n}");
                    foreach (Order o in c.Orders)
                    {
                        Write($" <{o.OrderId}.{o.Car.CarNickName}.{o.Customer.FirstName} {o.Customer.LastName}>");
                    }
                }
            WriteLine();

            ForegroundColor = ConsoleColor.DarkYellow;
            Write("-> Eager Loading:");
            n = 0;
            using (var context = new AutoLotEntities())
                foreach (Car c in context.cars.Include(c => c.Orders))
                {
                    Write($" {++n}");
                    foreach (Order o in c.Orders)
                    {
                        Write($" <{o.OrderId}.{o.Car.CarNickName}.{o.Customer.FirstName} {o.Customer.LastName}>");
                    }
                }
            WriteLine();
        }
예제 #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("***** Fun with ADO.NET EF Code First *****\n");

            //Database.SetInitializer(new MyDataInitializer());
            using (var context = new AutoLotEntities())
            {
                foreach (Inventory c in context.Cars)
                {
                    Console.WriteLine(c);
                }
            }

            Console.WriteLine("***** Using a Repository *****\n");
            using (var repo = new InventoryRepo())
            {
                foreach (Inventory c in repo.GetAll())
                {
                    Console.WriteLine(c);
                }
            }
            TestConcurrency();

            Console.ReadLine();
        }
예제 #5
0
        private static void FilterWithLINQ()
        {
            using (var context = new AutoLotEntities())
            {
                WriteLine("FilterWithLINQ()");

                // Get all data from the Inventory table.
                // could also write:
                // var allData = (from item in context.Inventories select item).ToArray();
                var allData = context.Inventories.ToArray();

                // Get a projection of new data.
                var colorsMakes = from item in allData select new { item.Color, item.Make };

                WriteLine("LINQ only colors and makes");
                foreach (var item in colorsMakes)
                {
                    WriteLine(item);
                }

                // Get only items where Color == "Black"

                WriteLine("LINQ only black cars");
                var blackCars = from item in allData
                                where item.Color == "Black"
                                select item;

                foreach (var item in blackCars)
                {
                    WriteLine(item);
                }
            }
        }
        //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);
                }
            }
        }
예제 #7
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);
            }
        }
예제 #8
0
        private static void FunWithLinqQueries()
        {
            using (var context = new AutoLotEntities())
            {
                var allData    = context.Cars.ToArray();
                var colorsMake = from item in allData
                                 select new
                {
                    item.Color,
                    item.Make
                };
                foreach (var item in colorsMake)
                {
                    Console.WriteLine(item);
                }

                Console.WriteLine();

                var blackCars = from item in allData where item.Color == "Black" select item;
                foreach (var item in blackCars)
                {
                    Console.WriteLine(item);
                }
            }
        }
예제 #9
0
        static void Main(string[] args)
        {
            Database.SetInitializer(new MyDataInitializer());

            Console.WriteLine("**** Fun with EF *******");

            using (AutoLotEntities context = new AutoLotEntities())
            {
                context.Cars.ToList().ForEach(car => Console.WriteLine(car));
            }
            Console.ReadLine();

            Console.WriteLine("**** Fun with repos ****");


            AddNewRecord(new Inventory()
            {
                Color = "Green", PetName = "Testy", Make = "Testy"
            });
            UpdateRecord(10);

            using (InventoryRepo ir = new InventoryRepo())
            {
                ir.GetAll().ForEach(x => Console.WriteLine(x));
            }

            TestConcurrency();
            Console.ReadLine();
        }
예제 #10
0
파일: Program.cs 프로젝트: SkyR1seR/AutoLot
        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;
                }
            }

        }
예제 #11
0
 private static void FindCar5()
 {
     using (var context = new AutoLotEntities())
     {
         WriteLine(context.Cars.Find(5));
     }
 }
        //private static void FunWithLinqQueries()
        //{
        //    using (var context = new AutoLotEntities())
        //    {
        //        // Get a projection of new data by using anonymous type object.
        //        // a`[] = {{Blue, BMW}, {White, VW}, .. }
        //        var colorsMakes = from item in context.Cars
        //                          select new { item.Color, item.Make };

        //        foreach (var item in colorsMakes)
        //        {
        //            WriteLine(item);
        //        }

        //        // Get only items where Color == "Black"
        //        var blackCars = from item in context.Cars where item.Color == "Black" select item;
        //        foreach (var item in blackCars)
        //        {
        //            WriteLine(item);
        //        }
        //    }
        //}

        private static void FunWithLinqQueries()
        {
            using (var context = new AutoLotEntities())
            {
                // Get all data from the Inventory table.
                // Could also write:
                // var allData = (from item in context.Cars select item).ToArray();
                var allData = context.Cars.ToArray();

                // Get a projection of new data by using anonymous type object.
                // a`[] = {{Blue, BMW}, {White, VW}, .. }
                var colorsMakes = from item in context.Cars
                                  select new { item.Color, item.Make };

                foreach (var item in colorsMakes)
                {
                    WriteLine(item);
                }

                // Get only items where Color == "Black"
                var blackCars = from item in context.Cars where item.Color == "Black" select item;
                foreach (var item in blackCars)
                {
                    WriteLine(item);
                }
            }
        }
예제 #13
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);
     }
 }
예제 #14
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);
         }
     }
 }
예제 #15
0
 private static void AddNewRecords(IEnumerable <Car> carsToAdd)
 {
     using (var context = new AutoLotEntities())
     {
         context.Cars.AddRange(carsToAdd);
         context.SaveChanges();
     }
 }
예제 #16
0
 private static void RemoveMultipleRecords(IEnumerable <Car> carsToRemove)
 {
     using (var context = new AutoLotEntities())
     {
         context.Cars.RemoveRange(carsToRemove);
         context.SaveChanges();
     }
 }
예제 #17
0
 public static void PrintInventoryUsingLinq()
 {
     using (AutoLotEntities context = new AutoLotEntities()) {
         (from car in context.Cars where car.Make == "VW" select new { CarId = car.CarId, Brand = car.Make }).ToList().ForEach(item => {
             Console.WriteLine(item);
         });
     }
 }
예제 #18
0
 public static void ClearData(AutoLotEntities context)
 {
     ExecuteDeleteSql(context, "Orders");
     ExecuteDeleteSql(context, "Customers");
     ExecuteDeleteSql(context, "Inventory");
     ExecuteDeleteSql(context, "CreditRisks");
     ResetIdentity(context);
 }
 static void RemoveMultipleRecords(IEnumerable <Car> carsToRemove)
 {
     using (var context = new AutoLotEntities())
     {
         //Каждая запись должна быть загружен в DbChangeTracker
         context.Cars.RemoveRange(carsToRemove);
         context.SaveChanges();
     }
 }
예제 #20
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();
     }
 }
예제 #21
0
 public static void PrintInventoryAsShortCar()
 {
     using (AutoLotEntities context = new AutoLotEntities()) {
         foreach (ShortCar car in context.Database.SqlQuery(typeof(ShortCar), "SELECT CarId AS Id, PetName AS CarNickName FROM Inventory"))
         {
             Console.WriteLine(car);
         }
     }
 }
예제 #22
0
 public static void PrintInventoryUsingQuery()
 {
     using (AutoLotEntities context = new AutoLotEntities()) {
         foreach (Car c in context.Cars.SqlQuery("SELECT CarID, Make, Color, PetName FROM Inventory WHERE Make = @p0", "BMW"))
         {
             Console.WriteLine(c);
         }
     }
 }
 private void ConfigureGrid()
 {
     using (AutoLotEntities context = new AutoLotEntities())
     {
         // Build a LINQ query that gets back some data from the Inventory table.
         var dataToShow = from c in context.Inventories select new { c.CarID, c.Make, c.Color, c.PetName };
         this.gridInventory.ItemsSource = dataToShow;
     }
 }
예제 #24
0
 public static void PrintInventory()
 {
     using (AutoLotEntities context = new AutoLotEntities()) {
         foreach (Car car in context.Cars)
         {
             Console.WriteLine(car);
         }
     }
 }
예제 #25
0
 private static void PrintShortCarRecord()
 {
     using (var context = new AutoLotEntities())
     {
         foreach (ShortCar c in context.Database.SqlQuery(typeof(ShortCar), "Select CarId, Make from Inventory"))
         {
             WriteLine(c);
         }
     }
 }
 static void PrintAllInventoryUseLinq()
 {
     using (var context = new AutoLotEntities())
     {
         foreach (Car car in context.Cars.Where(c => c.Make == "BMW"))
         {
             WriteLine(car);
         }
     }
 }
예제 #27
0
 private static void PrintAllInventory()
 {
     using (var context = new AutoLotEntities())
     {
         foreach (var item in context.Cars.Where(x => x.Make == "BMW"))
         {
             WriteLine(item);
         }
     }
 }
예제 #28
0
 private static void PrintAllInventory()
 {
     using (var context = new AutoLotEntities())
     {
         foreach (var elem in context.Cars)
         {
             WriteLine(elem);
         }
     }
 }
예제 #29
0
 private static void CallStoredProc() // Вызов хранимой процедуры
 {
     using (var entities = new AutoLotEntities())
     {
         // ObjectParameter inputParameter = new ObjectParameter("CarId", 83);
         var outputParameter = new ObjectParameter("petName", typeof(string));
         /*int petName = */ entities.GetPetName(83, outputParameter);
         Console.WriteLine("Car #83 is named {0}", outputParameter.Value);
     }
 }
예제 #30
0
        private static void ResetIdentity(AutoLotEntities context)
        {
            var tables = new[] { "Inventory", "Orders", "Customers", "CreditRisks" };

            foreach (var item in tables)
            {
                var rawSqlString = $"DBCC CHECKIDENT (\"dbo.{item}\",RESEED,-1";
                context.Database.ExecuteSqlRaw(rawSqlString);
            }
        }
예제 #31
0
 private static void PrintAllInventory()
 {
     using(AutoLotEntities context = new AutoLotEntities())
     {
         foreach (Car item in context.Cars)
         {
             Console.WriteLine(item);
         }
     }
 }
예제 #32
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();
                }
            }
        }
예제 #33
0
        static void Main(string[] args)
        {
            using (AutoLotEntities db = new AutoLotEntities())
            {
                try
                {
                    //IQueryable<> orderList = from order in db.Orders select order;
                    //Orders or = new Orders() { CarID = 1, CustID = 1, OrderID = 1 };
                    //db.Orders.Add(or);
                    //db.SaveChanges();
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
        }
예제 #34
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);
         }
     }
 }