sashomaga

using Entity Framework

Aug 2nd, 2013
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.26 KB | None | 0 0
  1. 1. create class library
  2. 2. manage NuGet -> entity framework
  3. 3. add new -> ADO.NET Entity Data Model -> Generate from Database -> new connection -> .(dot) /mean localhost/ => server name
  4. 4. create console application
  5. 5. add reference to class library and include it in using
  6. 6. manage NuGet -> installed packages -> entity framework(add for this project)
  7. 7. copy connection string from class library "App.config" and paste it into "App.config" in current project
  8.  
  9. //create instance of context
  10. NorthwindEntities db = new NorthwindEntities();
  11.  
  12. //LINQ
  13. foreach (var customer in db.Customers.Where(x => x.Country == "UK"))
  14. {
  15.     Console.WriteLine(customer.Address);
  16. }
  17.  
  18. //execute sql query
  19. var data = db.Customers.SqlQuery("SELECT * FROM dbo.CUSTOMERS").ToList();
  20. foreach (var row in data)
  21. {
  22.     Console.WriteLine(row.PostalCode);
  23. }
  24.  
  25.  //LINQ query
  26. using (var context = new NorthwindEntities())
  27. {
  28.     var customers = from c in context.Customers
  29.                     where c.City == "London"
  30.                     select c;
  31. }
  32.  
  33. //Extension Methods Query
  34. using (var context = new NorthwindEntities())
  35. {
  36.     var customersPhones = context.Customers.Where(c => c.City == "London").Select(c => c.Phone).ToList();
  37.     Console.WriteLine(customersPhones.Count());
  38. }
  39.  
  40. //several where selection
  41. using (var context = new NorthwindEntities())
  42. {
  43.     var customers = context.Customers.Where(c => c.Country == "UK");
  44.     customers = customers.OrderBy(x => x.ContactName);
  45.     customers = customers.Where(c => c.City == "London");
  46.     //query is accumulating and executes when is attempt for foreach or tolist
  47. }
  48.  
  49. //find by ID
  50. var customer = context.Customers.Find(2);
  51.  
  52. //anonymous type
  53. using (var context = new NorthwindEntities())
  54. {
  55.     var customersAddress = context.Customers.Where(c => c.City == "London").Select(x => new { x.Address });
  56.     foreach (var item in customersAddress)
  57.     {
  58.         Console.WriteLine(item.Address);
  59.     }                      
  60. }
  61.  
  62. //prints sql query //better use trace profiler
  63. Console.WriteLine(customers.ToString());
  64.  
  65. //add row to table
  66. using (var context = new NorthwindEntities())
  67.             {
  68.                 var region = new Region
  69.                 {
  70.                     RegionDescription = "Sofia"
  71.                 };
  72.                 context.Regions.Add(region);
  73.                 context.SaveChanges();
  74.             }
  75.            
  76. //cascade adding will add records to city table as well
  77. using (var db = new Database())
  78.             {
  79.                 Country spain = new Country();
  80.                 spain.population = "2 000 000";
  81.                 spain.Cities.Add(new City { name = "SomeTown" });
  82.                 spain.Cities.Add(new City { name = "OtherTown" });
  83.                 db.Contries.Add(spain);
  84.                 db.SaveChanges();
  85.             }
  86.            
  87. //delete
  88. using (var context = new NorthwindEntities())
  89.             {
  90.                 //var region = context.Regions.Find(9);
  91.                 var region = context.Regions.First(x => x.RegionID == 9);
  92.                 context.Regions.Remove(region);
  93.                 context.SaveChanges();
  94.             }
  95.             //if there is foreign key constraints I will get exception
  96.             //I can set options to cascade delete or set null
  97.            
  98. //update
  99. using (var context = new NorthwindEntities())
  100. {
  101.     var region = context.Regions.Find(9);
  102.     //var region = context.Regions.First(x => x.RegionID == 9);
  103.     region.RegionDescription = "new desc";
  104.     context.SaveChanges();
  105. }
  106.  
  107.  
  108. //extend and override methods (e.g. ToString()) by creating partial class with same name and override methods there
  109.  
  110. //parameterized native query
  111. private static IEnumerable<string> SelectEmployeeNamesByCountryAndCity(
  112.         string country, string city)
  113.     {
  114.         NorthwindEntities northwindEntities = new NorthwindEntities();
  115.         string nativeSqlQuery =
  116.             "SELECT FirstName + ' ' + LastName " +
  117.             "FROM dbo.Employees " +
  118.             "WHERE Country = {0} AND City = {1}";
  119.         object[] parameters = { country, city };
  120.         var employees = northwindEntities.Database.SqlQuery<string>(
  121.             nativeSqlQuery, parameters);
  122.         return employees;
  123.     }
  124.  
  125. //join tables  
  126. var customerSupplier =
  127.             from customer in northwindEntities.Customers
  128.             join supplier in northwindEntities.Suppliers
  129.             on customer.Country equals supplier.Country
  130.             select new
  131.             {
  132.                 CustomerName = customer.CompanyName,
  133.                 Supplier = supplier.CompanyName,
  134.                 Country = customer.Country
  135.             };
  136.  
  137. //join with extension methods
  138.  var customerSupplier =
  139.     northwindEntities.Customers.Join(
  140.     northwindEntities.Suppliers,
  141.     customer=>customer.Country),
  142.     (supplier=>supplier.Country),
  143.     (customer,supplier)=> new
  144.     {
  145.     CustomerName = customer.CompanyName,
  146.     Supplier = supplier.CompanyName,
  147.     Country = customer.Country
  148. });
  149.            
  150. //LINQ group
  151. var groupedCustomers =
  152.   from customer in northwindEntities.Customers
  153.   group customer by Customer.Country;
  154.  
  155. //extension methods group
  156. var groupedCustomers =
  157.   northwindEntities.Customers.GroupBy(
  158.     customer => customer.Country);
  159.    
  160. //attach (required for update)
  161. Product product = northwindEntities.Products.First(p => p.ProductID == id);
  162. //change product name
  163. northwindEntities.Products.Attach(product); // This line is required!
  164. product.ProductName = newName;
  165. northwindEntities.SaveChanges();
Advertisement
Add Comment
Please, Sign In to add comment