How to achieve entity framework in asp.net core using database first approach scaffolding mechanism reverse enginner (existing database)
Below mentioned tools required for this tutorial
· Visual studio 2017
· Core 2.0
· Sql server V18.2
Steps to achieve database first approach:
1. Open visual studio 2017 and create new ASP.NET Core MVC project in the name of MyDBFirstApp
2. Create database, table in sql server management studio
Database: ecommerce
Table: userdetails
CREATE TABLE [dbo].[userdetails](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[Password] [varchar](50) NULL,
[Mobile] [varchar](50) NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
3. Execute the below script in Package Manager Console
Scaffold-DbContext "Server=(local)\SQLEXPRESS01;Database=ecommerce;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Now model folder contains two more files in the name of ecommerceContext.cs, Userdetails.cs.
Update below mentioned code in ecommerceContext.cs class constructor
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace MyDBFirstApp.Models
{
public partial class ecommerceContext : DbContext
{
public virtual DbSet<Userdetails> Userdetails { get; set; }
public ecommerceContext(DbContextOptions<ecommerceContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Userdetails>(entity =>
{
entity.ToTable("userdetails");
entity.Property(e => e.Email)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Mobile)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Name)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Password)
.HasMaxLength(50)
.IsUnicode(false);
});
}
}
}
4. Create connection string in Appsetting.json file
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DevConnection": "Server=(local)\\SQLEXPRESS01;Database=ecommerce;Trusted_Connection=True;MultipleActiveResultSets=True;"
}
}
5. Configure db context connection string in startup.cs file ConfigureServices function.
services.AddDbContext<ecommerceContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MyDBFirstApp.Models;
using Microsoft.EntityFrameworkCore;
namespace MyDBFirstApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ecommerceContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
6. Right click the controller folder and create Mvc controller views using entity framework.
Now Asp.net Scaffolding code generation created all CRUD application-related files in View and controller folder.
Finally, run your asp.net core crud application using entity framework.
No comments:
Post a Comment