Creating Model For Existing Database Using Database First Approach In ASP.NET Core

In this article, we will create model for existing database using Database First approach In ASP.NET Core.

Prerequisites

Here we will create the entity and context classes of existing database in Entity Framework Core. Entity Framework Core does not support visual designer for database model and wizard to create the context and entity classes. EF Core supports Database-First approach via the Scaffold-DbContext command, this command scaffolds a DbContext and entity type classes of existing database. So, we will use Scaffold-DbContext command to do reverse engineering.

 

Install Necessary NuGet Packages

On the Tools menu point to NuGet Package Manager and then click Package Manager Console, run the following command in the Package Manager Console:

  1. SqlServer

Install-Package Microsoft.EntityFrameworkCore.SqlServer
  1. Tools

  • For Entity Framework Core 5
Install-Package Microsoft.EntityFrameworkCore.Tools
  • For Entity Framework Core 3.1
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.10

 

Now run the following command in the Package Manager Console to create entity classes and context class:

Scaffold-DbContext "server=.;database=Codehubs; Persist Security Info=True; Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

As the result, entity classes and context class are generated in Models folder.

The following is the auto generated CodehubsContext.cs context class for the Codehubs database.

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace DB_First.Models
{
    public partial class CodehubsContext : DbContext
    {
        public CodehubsContext()
        {
        }

        public CodehubsContext(DbContextOptions<CodehubsContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Article> Articles { get; set; }
        public virtual DbSet<Author> Authors { 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. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseSqlServer("server=.;database=Codehubs;  Persist Security Info=True; Integrated Security=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");

            modelBuilder.Entity<Article>(entity =>
            {
                entity.ToTable("Article");

                entity.HasOne(d => d.Author)
                    .WithMany(p => p.Articles)
                    .HasForeignKey(d => d.AuthorId)
                    .HasConstraintName("FK_Article_Author");
            });

            modelBuilder.Entity<Author>(entity =>
            {
                entity.ToTable("Author");

                entity.Property(e => e.Email).HasMaxLength(50);

                entity.Property(e => e.Name).HasMaxLength(50);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

The following is the auto generated Article.cs entity class for the Article table.

using System;
using System.Collections.Generic;

namespace DB_First.Models
{
    public partial class Article
    {
        public int Id { get; set; }
        public int? AuthorId { get; set; }

        public virtual Author Author { get; set; }
    }
}

The following is the auto generated Author.cs entity class for the Author table.

using System;
using System.Collections.Generic;

namespace DB_First.Models
{
    public partial class Author
    {
        public Author()
        {
            Articles = new HashSet<Article>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }

        public virtual ICollection<Article> Articles { get; set; }
    }
}

 

As you can see Model is created for my existing database Codehubs. Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check How To Connect SSMS To Local Default Instance

Submit a Comment

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

Subscribe

Select Categories