.NET Core

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

Yasin Panwala

Yasin Panwala is a Web Developer and Author at TheCodeHubs. He has experience in Web Developing and Designing and also in Writing. He has got his skills in working on technologies like .NET Core, ADO.NET, AJAX, Angular, AngularJS, ASP.NET, ASP.NET MVC, Bootstrap, C#, CSS, Entity Framework, Express.js, GraphQL, HTML, JavaScript, JQuery, JSON, LINQ, Microsoft Office, MongoDB, MySQL, Node.js, PostgreSQL, SQL, SQL Server, TypeORM, TypeScript, Visual Basic .NET, Web API. He also got his skills in working with different integration and some known versioning tools. He is always ready to learn new things and he always tries his best on tasks that are assigned to him and gives the best possible outputs.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago