locked
Need a good reference for LINQ and EF RRS feed

  • Question

  • User269416624 posted

    I'm on this new project where the database is generated from a data model - at least I think that's how it's generated - and we're using LINQ to access the data.  So far just about every data access thing I do seems like pure magic.  I don't really understand the data model - it doesn't look too much like a standard relational database to me - and it makes even less sense when I'm trying to query against it.  Most of what I do is look at examples that my dev lead has written to access data and try to copy those and modify them accordingly, but I sure don't understand how I'm getting the data that I'm getting.

    For over a decade now I've been used to extracting data using the old SQL method.  This LINQ/EF stuff is total greek to me.  In my early days of SQL I had a reference book that I referred to often until I got the hang of it.  Does anybody know of a good reference for understanding LINQ and EF?  It could be a web reference or paper - doesn't matter to me as long as it's helpful.

    Thursday, May 14, 2015 2:18 PM

Answers

  • User281315223 posted

    I've used something like this previously with regards to Lambda Expressions and LINQ, so it might be a useful in helping you understand how to use it :

    Lambda Expressions

    Lambda expressions are usable basically as long as you are using the available "method syntax" of LINQ within collections. You can think of them as just another way to use LINQ or another syntax that you could use to query objects or collections.

    For example, you could always use something like this :

    var query = from w in db.Widgets where w.WidgetId == yourWidgetId select w;

    but if you wanted to use the method syntax, you'll be more likely to use a lambda expression :

    var query = db.Widgets.Where(w => w.WidgetId == yourWidgetId);

    Lambda Expressions are basically anonymous functions that allow you to easily create delegates and map functions which can make querying databases or collections much easier. Let's go through an actual example below :

    //An array of integers 
    int[] integers = { 1 , 2, 3, 4, 5 };

    //Using LINQ to grab all of the odd values

    var odds = integers.Where(i => i % 2 == 1);

    We have an array of integers 1-5 and we are going to use a lambda expression within the Where clause to only grab the odd values that occur in the collection. To do this, we will use the following lambda expression : 

    i => i % 2 == 1

    Now what this does is actually create a mapping from i (which will represent each item within your collection) which will map to the function value on the other side of the "=>" which would yield the following results : 

    1 : (1 % 2) == 1 //yields true 
    2 : (2 % 2) == 1 //yields false
    3 : (3 % 2) == 1 //yields true
    4 : (4 % 2) == 1 //yields false
    5 : (5 % 2) == 1 //yields true

    so we can see that values 1, 3 and 5 result in true in our expression, which are in fact odd values. 

    The Where Clause will only return values that have an expression that results in true, which means that the following line of code would grab all of the odd values from your collection : 

    var odds = integers.Where(i => i % 2 == 1); //yields { 1, 3, 5 }

    Some Additional Details

    For instance in the example I provided earlier :

    var query = db.Widgets.Where(w => w.WidgetId == yourWidgetId);

    You could read this as from your collection of Widget objects (in db.Widgets), you would be getting all Widget objects (from the Where clause) such that the WidgetId property is equal to your yourWidgetId value or more basically :

    "Get all of the Widgets where the WidgetId property is equal to yourWidgetId"

    The lambda function itself is creating a mapping between each of the objects in the collection and you are providing it with a condition to check against. So you could try and break it down piece-by-piece into :

    db.Widgets                  # Your Widgets collection
    .Where(                     # The Where clause indicates we are going to get all Widgets in the collection that satisfy our lambda expression
    w                           # We will grab each Widget (w) in the collection...
    =>                          # such that...
    w.WidgetId == yourWidgetId  # the widgets WidgetId property (w.WidgetId) equals yourWidgetId evaluates to true
    );

    Learning LINQ

    101 LINQ Examples is a great place to start as it has tons of examples of different LINQ queries and will cover the code to help explain what is going on within the query. It starts out as very simple and progresses to more advanced queries.

    A few other things to check out might be : 

    If you are looking for a tool to help work with LINQ, consider downloading LinqPad. It's not only a great learning tool, but a pretty handy resource when dealing with real-world applications as well. It even has several areas within it site with some LINQ tutorials to handle some of the more advanced features in there like Mastering Linq.

    About Data Binding Specifically

    Entity Framework on a very basic level functions as a mapper (specifically an ORM, object relational mapper) and is going to map the schema of your tables and their relationships to actual entities (which are classes) that you can use within your code.

    For example, if you had a table called "Widgets" that consisted of two properties: WidgetId and WidgetName and you use Entity Framework to handle your relationships, this might generate a context that you would use to query your database and it would have a dataset available called Widgets. You could then use this context to query your data just as you might using SQL, except you no longer have to worry about manually mapping all of the columns :

    // Open your context (a bit like opening up a connection)
    using(var context = new YourContext())
    {
          // context is going to be your entire database and you'll be able to access individual tables
          // by their names
          
          // Get all of the widgets in your table
          var widgets = context.Widgets.ToList();
    
          // Likewise, you can query through LINQ, to only grab certain instances
          var widgetsThatStartWithN = context.Widgets.Where(w => w.WidgetName.StartsWith("W")).ToList();
    }

    This MSDN article might be helpful in introducing Entity Framework as well.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 2:37 PM
  • User37182867 posted

    Entity Framework is called an ORM (Object Relational Mapping). ORM's map relational database tables and columns to language specific classes and properties.

    The "pure magic" portion of it just encapsulates the data transitions it also converts LINQ (Language Integrated Query) into SQL for you. It works beautifully when it works.

    Here's a link to an article that explains it a little bit better.

    http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B

    Never mind - Rion posted while I was writing and his answer fully explains it i'm sure.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 2:38 PM

All replies

  • User281315223 posted

    I've used something like this previously with regards to Lambda Expressions and LINQ, so it might be a useful in helping you understand how to use it :

    Lambda Expressions

    Lambda expressions are usable basically as long as you are using the available "method syntax" of LINQ within collections. You can think of them as just another way to use LINQ or another syntax that you could use to query objects or collections.

    For example, you could always use something like this :

    var query = from w in db.Widgets where w.WidgetId == yourWidgetId select w;

    but if you wanted to use the method syntax, you'll be more likely to use a lambda expression :

    var query = db.Widgets.Where(w => w.WidgetId == yourWidgetId);

    Lambda Expressions are basically anonymous functions that allow you to easily create delegates and map functions which can make querying databases or collections much easier. Let's go through an actual example below :

    //An array of integers 
    int[] integers = { 1 , 2, 3, 4, 5 };

    //Using LINQ to grab all of the odd values

    var odds = integers.Where(i => i % 2 == 1);

    We have an array of integers 1-5 and we are going to use a lambda expression within the Where clause to only grab the odd values that occur in the collection. To do this, we will use the following lambda expression : 

    i => i % 2 == 1

    Now what this does is actually create a mapping from i (which will represent each item within your collection) which will map to the function value on the other side of the "=>" which would yield the following results : 

    1 : (1 % 2) == 1 //yields true 
    2 : (2 % 2) == 1 //yields false
    3 : (3 % 2) == 1 //yields true
    4 : (4 % 2) == 1 //yields false
    5 : (5 % 2) == 1 //yields true

    so we can see that values 1, 3 and 5 result in true in our expression, which are in fact odd values. 

    The Where Clause will only return values that have an expression that results in true, which means that the following line of code would grab all of the odd values from your collection : 

    var odds = integers.Where(i => i % 2 == 1); //yields { 1, 3, 5 }

    Some Additional Details

    For instance in the example I provided earlier :

    var query = db.Widgets.Where(w => w.WidgetId == yourWidgetId);

    You could read this as from your collection of Widget objects (in db.Widgets), you would be getting all Widget objects (from the Where clause) such that the WidgetId property is equal to your yourWidgetId value or more basically :

    "Get all of the Widgets where the WidgetId property is equal to yourWidgetId"

    The lambda function itself is creating a mapping between each of the objects in the collection and you are providing it with a condition to check against. So you could try and break it down piece-by-piece into :

    db.Widgets                  # Your Widgets collection
    .Where(                     # The Where clause indicates we are going to get all Widgets in the collection that satisfy our lambda expression
    w                           # We will grab each Widget (w) in the collection...
    =>                          # such that...
    w.WidgetId == yourWidgetId  # the widgets WidgetId property (w.WidgetId) equals yourWidgetId evaluates to true
    );

    Learning LINQ

    101 LINQ Examples is a great place to start as it has tons of examples of different LINQ queries and will cover the code to help explain what is going on within the query. It starts out as very simple and progresses to more advanced queries.

    A few other things to check out might be : 

    If you are looking for a tool to help work with LINQ, consider downloading LinqPad. It's not only a great learning tool, but a pretty handy resource when dealing with real-world applications as well. It even has several areas within it site with some LINQ tutorials to handle some of the more advanced features in there like Mastering Linq.

    About Data Binding Specifically

    Entity Framework on a very basic level functions as a mapper (specifically an ORM, object relational mapper) and is going to map the schema of your tables and their relationships to actual entities (which are classes) that you can use within your code.

    For example, if you had a table called "Widgets" that consisted of two properties: WidgetId and WidgetName and you use Entity Framework to handle your relationships, this might generate a context that you would use to query your database and it would have a dataset available called Widgets. You could then use this context to query your data just as you might using SQL, except you no longer have to worry about manually mapping all of the columns :

    // Open your context (a bit like opening up a connection)
    using(var context = new YourContext())
    {
          // context is going to be your entire database and you'll be able to access individual tables
          // by their names
          
          // Get all of the widgets in your table
          var widgets = context.Widgets.ToList();
    
          // Likewise, you can query through LINQ, to only grab certain instances
          var widgetsThatStartWithN = context.Widgets.Where(w => w.WidgetName.StartsWith("W")).ToList();
    }

    This MSDN article might be helpful in introducing Entity Framework as well.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 2:37 PM
  • User37182867 posted

    Entity Framework is called an ORM (Object Relational Mapping). ORM's map relational database tables and columns to language specific classes and properties.

    The "pure magic" portion of it just encapsulates the data transitions it also converts LINQ (Language Integrated Query) into SQL for you. It works beautifully when it works.

    Here's a link to an article that explains it a little bit better.

    http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B

    Never mind - Rion posted while I was writing and his answer fully explains it i'm sure.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 2:38 PM
  • User269416624 posted

    Thanks to both of you for those responses - that will give me some good info to look at for a while!  :)

    Thursday, May 14, 2015 3:02 PM
  • User37182867 posted

    your'e welcome

    Friday, May 15, 2015 10:14 AM