Introduction to Entity Framework

Leave a comment

Microsoft’s Entity Framework is an Object Relational Mapping (ORM) framework for ADO.NET. Let’s go through an example of how to use Entity Framework.

First, we will create a new Console application project:

Go to Manage NuGet Packages for Solution:

And select EntityFramework:

Select the project and Install:

Click OK and Accept:

You will see the following messages:

Once complete, you will see these new references in your project:

We can now connect this to our database and write some code. We have a database WideWorldImporters that we can connect to.

Select Add New Item:

Select Data and then ADO.NET Entity Data Model. We will call our model WideWorldEF:

Here we have different options for our model contents:

Select the first option and click Next.

Now we select the data connection:

Click Next:

Now we can select our Database Objects and Settings. You can see how this matches to our database:

We will select the Customers table:

Click Finish. You will now see the model loaded into your environment.

You can now use the code below to print each customer to the console app:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Carl.EntityFramework.Sample1
{
    class Program
    {
        static void Main(string[] args)
        {
            WideWorldImportersEntities db = new WideWorldImportersEntities();
            var query = from cust in db.Customers
                        select cust;
            List<Customer> custList = query.ToList();
            foreach (Customer c in custList)
            {
                Console.WriteLine(c.CustomerName);
            }
            Console.ReadLine();
        }
    }
}

You can see how simplified it is to connect to the database and perform a read operation. You can also easily perform CRUD operations.

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

Leave a Reply

Your email address will not be published. Required fields are marked *