Entity Framework Getting started with Entity Framework Using Entity Framework from C# (Code First)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Code first allows you to create your entities (classes) without using a GUI designer or a .edmx file. It is named Code first, because you can create your models first and Entity framework will create database according to mappings for you automatically. Or you can also use this approach with existing database, which is called code first with existing database For example, if you want a table to hold a list of planets:

public class Planet
{
    public string Name { get; set; }
    public decimal AverageDistanceFromSun { get; set; }
}

Now create your context which is the bridge between your entity classes and the database. Give it one or more DbSet<> properties:

using System.Data.Entity;

public class PlanetContext : DbContext
{
    public DbSet<Planet> Planets { get; set; }
}

We can use this by doing the following:

using(var context = new PlanetContext())
{
    var jupiter = new Planet 
    {
        Name = "Jupiter", 
        AverageDistanceFromSun = 778.5
    };

    context.Planets.Add(jupiter);
    context.SaveChanges();
}

In this example we create a new Planet with the Name property with the value of "Jupiter" and the AverageDistanceFromSun property with the value of 778.5

We can then add this Planet to the context by using the DbSet's Add() method and commit our changes to the database by using the SaveChanges() method.

Or we can retrieve rows from the database:

using(var context = new PlanetContext())
{
    var jupiter = context.Planets.Single(p => p.Name == "Jupiter");
    Console.WriteLine($"Jupiter is {jupiter.AverageDistanceFromSun} million km from the sun.");
}


Got any Entity Framework Question?