In this article I will explain a simple tutorial with an example, how to use Entity Framework Code First Approach with existing Database in ASP.Net Core MVC.
This article will explain how to configure Entity Framework Code first from database in ASP.Net Core MVC.
Note: For beginners in ASP.Net Core MVC and Entity Framework, please refer my article ASP.Net Core: Simple Entity Framework Tutorial with example.
 
 
Database
1. First you need to download the SQL file using the following link.
2. Once downloaded, you need to execute the SQL file in SQL Server Management Studio.
3. After execution you will see the following Database.
ASP.Net Core MVC: EntiyFramework Code First Approach with Existing Database
 
The Database also contains the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
ASP.Net Core MVC: EntiyFramework Code First Approach with Existing Database
 
The Table consists of following records.
ASP.Net Core MVC: EntiyFramework Code First Approach with Existing Database
 
 
Creating new ASP.Net Core MVC Project
For more details on creating ASP.Net Core MVC project, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Configuring and connecting Entity Framework Code First from database
Now I will explain the steps to configure and connect Entity Framework Code first from database.
In order to generate the Entity Framework Code first model from existing database Table in ASP.Net MVC Core, the Scaffold-DbContext command is used.
Note: In order for Scaffold-DbContext to generate an entity type, the database table must have a primary key.
 
Scaffold-DbContext has the following parameters:
1. Connection – It specifies the Connection String to the Database.
2. Provider – It specifies the Provider name to be used. In this case it is Microsoft.EntityFrameworkCore.SqlServer.
3. OutputDir – It specifies to set the Folder (Directory) where the classes will be generated. In this case it is set with Models Folder.
4. DataAnnotations – It specifies to use DataAnnotation attributes to configure the model.
Note: For more details on Scaffold-DbContext, please refer the link Scaffold-DbContext.
 
Now let’s run the Scaffold-DbContext command from Nuget Package Manager Console window using the following command.
Scaffold-DbContext "Data Source=.\SQL2019;Initial Catalog=CodeFirst;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -DataAnnotations
ASP.Net Core MVC: EntiyFramework Code First Approach with Existing Database
 
After successfully executed the command, the Models folder will look as shown below.
ASP.Net Core MVC: EntiyFramework Code First Approach with Existing Database
 
Finally, the Entity Model is ready with the following classes.
Generated Table class
public partial class Customers
{
    [Key]
    public int CustomerId { get; set; }
 
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
 
    [Required]
    [StringLength(50)]
    public string Country { get; set; }
}
 
Generated Database Context
public partial class CodeFirstContext : DbContext
{
    public CodeFirstContext()
    {
    }
 
    public CodeFirstContext(DbContextOptions<CodeFirstContext> options)
        : base(options)
    {
    }
 
    public virtual DbSet<Customers> Customers { get; set; }
 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
            optionsBuilder.UseSqlServer("Data Source=.\\SQL2019;Initial Catalog=CodeFirst;Trusted_Connection=True;");
        }
    }
 
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customers>(entity =>
        {
            entity.Property(e => e.Country).IsUnicode(false);
 
            entity.Property(e => e.Name).IsUnicode(false);
        });
    }
}
 
 
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, the Customer records are fetched from database using Entity Framework Code First Approach and returned to the View.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        using (CodeFirstContext context = new CodeFirstContext())
        {
            List<Customers> customers = (from customer in context.Customers
                                        select customer).ToList();
            return View(customers);
        }
    }
}
 
 
View
Inside the View, in the very first line the Customer Model is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@using EF_CodeFirst_Core_MVC.Models;
@model IEnumerable<Customers>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>CustomerId</th>
            <th>Name</th>
            <th>Country</th>
        </tr>
        @foreach (Customers customer in Model)
        {
            <tr>
                <td>@customer.CustomerId</td>
                <td>@customer.Name</td>
                <td>@customer.Country</td>
            </tr>
        }
    </table>
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: EntiyFramework Code First Approach with Existing Database
 
 
Downloads