LINQ & EF Core

What is SQL?

What if we bring the power of SQL to arrays?

LINQ

 Language-Integrated Query

Create

SQL-esque expressions that work on anything that is an IEnumerable

like map, filter and reduce

  public class Movie {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Tagline { get; set; }
    public DateTime ReleasedDate { get; set; }
    public int Screenings { get; set; }
    public double PricePerTicket { get; set; }
    public double TotalRevenue { get; set; }
    public double Cost { get; set;}
    public double Budget { get; set;}
 }
 
 // stored in a IEnumerable
 var movies = new List<Movie>();
  • Select

  • Where

  • Aggregate

  • First 

  • Sum

  • Max/Min

  • OrderBy

common linq queries

using System.Linq;
    
// other code.....
    
var yearAndMovie = 
    movies.Select(movie => movie.ReleaseDate.Year);

Select

    using System.Linq;
    
    // other code.....
    
    var popularMovies = 
    	movies.Where(movie => movie.Screenings >= 100);

where

using System.Linq;   
  
  //find the movie with the highest revenue
  var totalRevenue = 
    movies
        .Aggregate(0, (current, next) => next + current.TotalRevenue);
         

Aggregate

using System.Linq;   
  
var favoriteMovie = movies
	.First(movie => movie.Title == "Jaws");

First

using System.Linq;   
  
var favoriteMovie = movies
	.FirstOrDefault(movie => movie.Title == "Jaws");

FirstOrDefault

using System.Linq;   
  
var total = movies.Sum(movie => movie.TotalRevenue);


Sum

using System.Linq;   
  
var biggestBudget  =  movies.Max(movie => movie.Budget);
var smallestBudget  =  movies.Min(movie => movie.Budget);



Max/Min

using System.Linq;   
  
var alphabetically = movies.OrderBy(movie => movie.Title);




OrderBy

using System.Linq;   

var sorted = movies
	.OrderBy(movie => movie.Title)
	.ThenBy(movie => move.DateReleased);





OrderBy & ThenBy

 

EF Core

Entity Framework Core

EF Core is an ORM that allows developers to use SQL in C#

ORMs allows us to model our database using POCOs and query the database using LINQ

time to get our hands dirty

LINQ & EF Core

By Mark Dewey

LINQ & EF Core

  • 15
Loading comments...

More from Mark Dewey