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(); }
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); } }
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(); }
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(); }
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); } } }
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); } }
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); } } }
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(); }
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; } } }
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); } } }
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); } }
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); } } }
private static void AddNewRecords(IEnumerable <Car> carsToAdd) { using (var context = new AutoLotEntities()) { context.Cars.AddRange(carsToAdd); context.SaveChanges(); } }
private static void RemoveMultipleRecords(IEnumerable <Car> carsToRemove) { using (var context = new AutoLotEntities()) { context.Cars.RemoveRange(carsToRemove); context.SaveChanges(); } }
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); }); } }
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(); } }
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(); } }
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); } } }
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; } }
public static void PrintInventory() { using (AutoLotEntities context = new AutoLotEntities()) { foreach (Car car in context.Cars) { Console.WriteLine(car); } } }
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); } } }
private static void PrintAllInventory() { using (var context = new AutoLotEntities()) { foreach (var item in context.Cars.Where(x => x.Make == "BMW")) { WriteLine(item); } } }
private static void PrintAllInventory() { using (var context = new AutoLotEntities()) { foreach (var elem in context.Cars) { WriteLine(elem); } } }
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); } }
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); } }
private static void PrintAllInventory() { using(AutoLotEntities context = new AutoLotEntities()) { foreach (Car item in context.Cars) { Console.WriteLine(item); } } }
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(); } } }
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; } } }
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); } } }