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:

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

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:

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

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

The GitHub code is here. Enjoy!


Tagged with: , , ,