Entity framework Core CRUD example

In this blog, we will get a detailed look about Entity Framework Core, and we will also perform CRUD operation with ASP.Net MVC Core using Entity Framework Core.

What is Entity Framework Core (EF Core) ?

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

EF Core support LINQ and supports databases like SQL Server, SQL Azure, MySQL, Postgre SQL. EF Core version 5 and 6 works 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, first is database-first approach and second is code-first. 

Nuget Packages for Database Providers in Entity Framework Core.

Database Providers Nuget Package
SQL Server Microsoft.EntityFrameworkCore.SqlServer
MySQL MySql.Data.EntityFrameworkCore
SQL Lite Microsoft.EntityFrameworkCore.SQLite


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

Entity Framework Core CRUD Tutorial

  1. Database-first approach
  2. Add a model class to map the table fields.
  3. Create a connection in MVC Core application
  4. Create a DbSet property to write LINQ query
  5. Add or Create Controller class
  6. List or 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 sample 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 listing.


2. Create Model class 

Now, create a class that have exactly 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 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 in 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 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 below code in this class.

Note: 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 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 controller class within our project. You may either add an empty controller class or a controller class with read/write actions or 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 next screen, select your Model class and Data Context class available in your project.


In 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  

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

 7. Action method to insert data

    [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

   [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

     [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 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 item available in database.

You can perform Create, Edit, Delete operation from there.

Summary

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

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

To work with database-first approach, create a table in 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.

Comments