Entity framework Core CRUD example with ASP.Net MVC Core

In this blog, we will get a detailed look about Entity framework Core CRUD example with ASP.Net MVC Core.

What is Entity Framework Core (EF Core)?

EF Core or Entity Framework Core is a new database object mapper for the .Net framework. It is lightweight and open source as well as supports all platforms.

EF Core support LINQ and supports databases like SQL Server, SQL Azure, MySQL, and Postgre SQL. EF Core versions 5 and 6 work only with .Net Core.

 Development Approach in Entity Framework Core

Like the older version of Entity Framework, two types of approaches can be taken in Entity Framework Core, the first is a database-first approach and the second is code-first.

Nuget Packages for Database Providers in Entity Framework Core.

Database ProvidersNuget Package
SQL ServerMicrosoft.EntityFrameworkCore.SqlServer
MySQLMySql.Data.EntityFrameworkCore
SQL LiteMicrosoft.EntityFrameworkCore.SQLite

To understand the Entity Framework Core in this article, I have sampled a live project code.

Entity Framework Core CRUD example with ASP.Net MVC Core

  1. Database-first approach
  2. Add a model class to map the table fields.
  3. Create a connection in the MVC Core application
  4. Create a DbSet property to write LINQ query
  5. Add or Create a Controller class
  6. List of Read Action method
  7. Save or Create action method
  8. Edit action method
  9. Delete action method

1 . Database-First approach

In Entity Framework Core, this is called Database-First Approach, in this, we first create our table in the database and then we create a class to map the entity to the table.

In this article, I will show you code samples and steps with a database of a live project. This project is based on advertisement listing.

Below is a table structure that I have done for the listing.

2. Create a Model class

Now, create a class that has exactly the same properties.

ListingModel Class

public class ListingModel
    {
        [Key]
        public int Id { get; set; }
        public int ListOrder { get; set; }
        public string ListName { get; set; }
        public string OwnerName { get; set; }
        public string Category { get; set; }
        public int type { get; set; }
        public string Image { get; set; }
        public string Contact { get; set; }
        public string Email { get; set; }
        public string Location { get; set; }
        public string MoreDetails { get; set; }
        public string Youtube { get; set; }
        public string Facebook { get; set; }
        public string Twitter { get; set; }
        public string Instagram { get; set; }
        public string Website { get; set; }
    }

3. Create a Database connection

You do not have a web.config file like .Net, there you will find a JSON-based file called appsettings.json, which is at the root of your project.

Add a connection string as shown below.

{
  "ConnectionStrings": {
   "DefaultConnection": "Server=localhost\SQLEXPRESS;Database=BRAd;Trusted_Connection=Yes;Integrated Security=SSPI;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Create a folder with the name Data.

Add a DBInitializer class inside this folder.

public class DbInitializer
    {
        internal static void Initialize(MyDataContext context)
        {
            throw new NotImplementedException();
        }
    }

4. DbSet Property in Data Context

Create a MyDBContext class which dervies DbContext class provided by Entity Framework Core.

Add the below code in this class.

Note: The string name given in “is the same name as your table.

Now, we will add a DbSet property of type <TEntity> here. We have created the DbSet<ListingModel> property.

A DbSet in Entity Framework Core is used to query or save data using LINQ.

   public class MyDataContext:DbContext
    {
        public MyDataContext(DbContextOptions<MyDataContext> options) : base(options)
        {
        }
        public DbSet<ListingModel> MotihariListing { get; set; }
       

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ListingModel>().ToTable("MotihariListing");
           
        }
    }

Add below namespace

using Microsoft.EntityFrameworkCore;

In startup.cs

 services.AddDbContext<MyDataContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Find route details in Startup.cs file

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

5. Now, add a controller class within your project.

We will add a controller class to our project. You may either add an empty controller class a controller class with read/write actions or an MVC controller with views, using Entity Framework.

I have selected 3rd option i.e. MVC Controller with views, using Entity Framework.

This will create all action methods (Creates, List, Update, Delete, Details) within your controller for you automatically with corresponding views.

From the next screen, select your Model class and Data Context class available in your project.

In the Controller class, note that a variable of type DataContext is declared.

private readonly MyDataContext _context;
 
        public ListingModelsController(MyDataContext context)
        {
            _context = context;
        }

6. List or Read action method

This action method is to read the data from a table and display the list of records on view.

     // GET: ListingModels
        public async Task Index()
        {
            return View(await _context.ListingModel.ToListAsync());
        }

 7. Action method to insert data

This action method is of POST type and will insert a record into the table.

    [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Create([Bind("Id,ListOrder,ListName,OwnerName,Category,type,Image,Contact,Email,Location,MoreDetails,Youtube,Facebook,Twitter,Instagram,Website")] ListingModel listingModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(listingModel);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(listingModel);
        }

 whenever the SaveChanges() method of DbContextmethod is called,  all entities will be inserted into the database.

8. Edit HttpPost Action method

This action method will update the existing record with the entity framework core.

To do this, you can use SaveChangesAsync() method.

   [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Edit(int id, [Bind("Id,ListOrder,ListName,OwnerName,Category,type,Image,Contact,Email,Location,MoreDetails,Youtube,Facebook,Twitter,Instagram,Website")] ListingModel listingModel)
        {
            if (id != listingModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(listingModel);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ListingModelExists(listingModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(listingModel);
        }

9. Delete HttpPost Action Method

Action method to delete a record based on the input parameter.

     [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task DeleteConfirmed(int id)
        {
            var listingModel = await _context.ListingModel.FindAsync(id);
            _context.ListingModel.Remove(listingModel);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

Below is the combined code for the Controller class.

namespace EFCoreDemo.Controllers
{
    public class ListingModelsController : Controller
    {
        private readonly MyDataContext _context;

        public ListingModelsController(MyDataContext context)
        {
            _context = context;
        }

        // GET: ListingModels
        public async Task<IActionResult> Index()
        {
            return View(await _context.ListingModel.ToListAsync());
        }

        // GET: ListingModels/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var listingModel = await _context.ListingModel
                .FirstOrDefaultAsync(m => m.Id == id);
            if (listingModel == null)
            {
                return NotFound();
            }

            return View(listingModel);
        }

        // GET: ListingModels/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: ListingModels/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,ListOrder,ListName,OwnerName,Category,type,Image,Contact,Email,Location,MoreDetails,Youtube,Facebook,Twitter,Instagram,Website")] ListingModel listingModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(listingModel);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(listingModel);
        }

        // GET: ListingModels/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var listingModel = await _context.ListingModel.FindAsync(id);
            if (listingModel == null)
            {
                return NotFound();
            }
            return View(listingModel);
        }

        // POST: ListingModels/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,ListOrder,ListName,OwnerName,Category,type,Image,Contact,Email,Location,MoreDetails,Youtube,Facebook,Twitter,Instagram,Website")] ListingModel listingModel)
        {
            if (id != listingModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(listingModel);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ListingModelExists(listingModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(listingModel);
        }

        // GET: ListingModels/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var listingModel = await _context.ListingModel
                .FirstOrDefaultAsync(m => m.Id == id);
            if (listingModel == null)
            {
                return NotFound();
            }

            return View(listingModel);
        }

        // POST: ListingModels/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var listingModel = await _context.ListingModel.FindAsync(id);
            _context.ListingModel.Remove(listingModel);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ListingModelExists(int id)
        {
            return _context.ListingModel.Any(e => e.Id == id);
        }
    }
}

Once you run your page, you can see the list of items available in the database.

You can perform Create, Edit, and Delete operations from there.

Summary

Entity Framework Core is a new version of Entity Framework and the latest version of EF Core is 6.

EF Core is an open-source and platform-independent database-object mapping framework.

To work with the database-first approach, create a table in the SQL server database and add a model class to map the table fields.

Hope you like this article.

Do share it in your friends’ community, and if there is some feedback, write in the comment box below.

Please follow and like us:

Leave a Comment