ASP.NET Core

CRUD Operation in ASP.Net Core

Create, Update, Delete & Retrieve in Asp.net Core

  • Create a New Project
  • In Left hand Side Visual C#  > .Net Core
  • Right hand sideASP.Net Core Web Application
  • Give the project name and Path
  • Click on Next

  • Select WebApplication (Modal View controller)
  • Click Ok

  • Create a Class in modal folder that is entity.cs

Add Name space

using Microsoft.EntityFrameworkCore;
  • Extend Entity class with DbContext like
public class Entity: DbContext
  • Create parameterized constructor Like
    public Entity(DbContextOptions<Entity> options)
                : base(options)
           { }
    
  • Create another entity class in same file. Like
 public class Emp
    {
        public int EmpId { get; set; }
        public string Name { get; set; }
        public string EmailID { get; set; }
        public string ContactNo { get; set; }
    }
  • Create DbSet for emp in entity class  like
      public DbSet<Emp> Emp { get; set; }

     

  • Finally Modal entity class look like below
  • public class Entity: DbContext
        {
            public Entity(DbContextOptions<Entity> options): base(options){ }
            public DbSet<Emp> Emp { get; set; }
        }
        public class Emp
        {
            public int EmpId { get; set; }
            public string Name { get; set; }
            public string EmailID { get; set; }
            public string ContactNo { get; set; }
        }

     

  • Now go to startup.cs file
  • Add namespace of you recently created entity modal class like
using WebApplication_CRUD.Models;
  • Add another namespace of entity framework like
using Microsoft.EntityFrameworkCore;
  • Add below code in configure service method
    var connection = @"Server=00.000.000.00,1533;Initial Catalog=crud_demo;Persist Security Info=True;Connect Timeout=15;User ID=sa;Password=7hfgLmG$wtsL6x";
            services.AddDbContext<Entity>(options => options.UseSqlServer(connection));
  • Final Code of startup.cs file should be
    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.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                var connection = @"Server=00.000.000.00,1533;Initial Catalog=crud_demo;Persist Security Info=True;Connect Timeout=15;User ID=sa;Password=7hfgLmG$wtsL6x";
                services.AddDbContext<Entity>(options => options.UseSqlServer(connection));
    
            }
    
            // 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();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseCookiePolicy();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }

     

  • Before go to next step Make sure you have created database as per above connection string
  • Go to Tools à Nuget Package Manager à Package Manager Console
  • Fire below command in your package manager console
    add-migration fist_initial
    • If command succedd then migraton folder will create in your application
    • Fire below command in console package manager for operation on your database
      update-database
      • Go to your database & check emp table has created or not
      • If created then we are correct

 

  • Create controller with Views, Using entity Framework
  • Cleck on Next
  • Select your entity class recently you added in Entity.cs file
  • Select data content class
  • Click on Add Button

 

Additional screen shot for your reference

 

Show More

Related Articles

Leave a Reply

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

Close