Entity Framework – Linq vs Extension Methods (Example)

This article presents a simple example of querying with Linq and Extension Methods in Entity Framework (EF).

To set the EF, create a C# Console application. Then add the Package Manager Console from Tools:

Then run Install-Package EntityFramework in the Package Manager Console, selecting correctly the Default project. The EF libraries should appear in the references:

So, once the EF is added to the project we need to add a class for its tables. In our example, it would be one class only, as one table is quite enough:

using System;
using System.Collections.Generic;

namespace SomeDbProject
{
    class Car
    {
        public int ID { get; set; }
        public string Model { get; set; }
        public decimal Price { get; set; }
        public string Origin { get; set; }
        public int Year { get; set; }

        public string GetModel(int value)
        {
            int modelDefined = value % 5;
            List carModels = new List { "Ferrari", "Porsche", "Lada", "Opel", "VW" };
            return carModels[modelDefined];
        }

        public string GetOrigin(int value)
        {
            int originDefined = value % 5;
            List carOrigin = new List { "Italy", "Sicily", "Russia", "Germany", "Bulgaria" };
            return carOrigin[originDefined];
        }

        public int GetYear(int value)
        {
            Random rnd = new Random();
            return rnd.Next(1900+value, 2000 +value);
        }

        public decimal GetPrice(int value)
        {
            Random rnd = new Random();
            return rnd.Next(value * 100, value * 1000);
        }

        public override string ToString()
        {
            return $"{ID} \t {Model} \t EUR {Price} \t {Origin} \t {Year}";
        }
    }
}

This is how the connection String in App.Config looks like for MSSQLLocalDB:

  
    LocalDb)\MSSQLLocalDB;initial catalog=SomeDbProject.DbContext;integrated security=True;" providerName="System.Data.SqlClient" />

The class SomeDBContext includes an inheritance from DbContext (coming from System.Data.Entity of EF). The reference of the Car class is needed, to inform EF that a table called Cars should be cretated. If it was a foreign key, it should have been virtual:

namespace SomeDbProject
{
    using System.Data.Entity;

    class SomeDbContext : DbContext
    {
        public SomeDbContext() : base("name=SomeDbProjectConnectionString")
        {
            Database.SetInitializer(new DropCreateDatabaseAlways());
        }
        public DbSet  Cars { get; set; }
    }
}

Finally, this is the StartUp class, which initializes the DB and creates 1000 units in the DB:

using System;
using System.Linq;

namespace SomeDbProject
{
    class StartUp
    {
        static void Main()
        {
            SomeDbContext context = new SomeDbContext();

            for (int i = 0; i < 1000; i++)
            {
                Car newCar = new Car();
                newCar.Model = newCar.GetModel(i);
                newCar.Origin = newCar.GetOrigin(i);
                newCar.Price = newCar.GetPrice(i);
                newCar.Year = newCar.GetYear(i);
                context.Cars.Add(newCar);
            }
            context.SaveChanges();

            //LINQ
            Console.WriteLine("LINQ:\n");
            var queryFerrari =
                from c in context.Cars
                where c.Model.Contains("Ferrari")
                orderby c.Price
                select c;

            foreach (Car myCar in queryFerrari)
            {
                Console.WriteLine(myCar);
            }

            //Extension method
            Console.WriteLine("\n\nExtentsion method:");
            var queryBulgaria = context.Cars
                .Where(c => c.Origin.Contains("Bulgaria"))
                .OrderBy(c => c.Price);

            foreach (Car myCar in queryBulgaria)
            {
                Console.WriteLine(myCar);
            }
        }
    }
}

As you see LINQ and the extension method work both quite fast:

The GitHub code is here. Enjoy!