C# – EF – Beginning with Entity Framework

What is Entity Framework? If we take a look at Wikipedia, it says Entity Framework (EF) is an open source object-relational mapping (ORM) framework for ADO.NET.

What does it mean? Pretty much, magic. 🙂 You make some classes in C# and the EF maps those classes to a table. Furthermore, you may query those classes and get results. Without using SQL, the EF writes the SQL for you. That’s it!

I have decided to build up a small example of EF, showing how the “magic” works. Let’s imagine that we have to build a table with three products in it. Something like this:

ef

The products have Id, Name, Features, Description and Price.

Thus, in C# you make a class called Products.cs and you add the following in it:

That’s all – one constructor and 5 fields.

Then, in the main method, using the constructor write the following:

After all is said and done, you need to make the connection to the database. Press Ctrl+Shift+A and select ADO.Net Entity Data Model. 

Capture

Then put a meaningful name and select next

 

emptyCodeFirstModel

You will get a new class with the name you have selected. Mine is looking like this, after a bit of customization:

With this one, you may run your code to get the new data in the database. This is what I got after pressing F5 a few times:

Capture2

Yup. Not very meaningful, but exactly what I have expected.

How to make queries through C# in the Database?

If we want to make a simple SQL query in the database, here is a really simple and understandable solution. Make a connection, make a string for the query and execute the query with the SqlCommand class. Something like this:

The result would be a well formatted table of Lenovo Ultra and Dell Old, as far as they are the only laptops I had with a price above 500.

dbLess

Yup. It looks nice and it is nice, when it works! 🙂

Cheers!

 

 

About

A VBA Developer.

Tagged with: , ,