Sunday, July 19, 2020

Web API : CRUD operation using repository pattern .net framework

In this article I am going to explain how to create Web API CRUD (create, read, update, delete) operation using repository pattern .net framework.

 

In previous I have explained how to create First Web API Hello World application with repository pattern and how to return data in JSON format from ASP.NET Web API.

 

Here in this article I am going to create Web API with CRUD operations for Article with Title, description and tags fields.

Prerequisites

-          -Visual Studio 2019

I am using repository pattern to create Web API and .net framework.

To set up repository pattern check this article how to create First Web API Hello World application with repository pattern .

So let’s start create Web API. First of all, create connectionstring in web.config.

<add name ="dbconnection" connectionString="data source=.;initial catalog=Aspmantra;
Integrated Security=True" providerName="System.Data.SqlClient"/>

 

Now create a class in model (Article.cs)



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WEBAPI.Models
{
[Table("tblArticle")]
public class Article
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ArticleId { get; set; }
public string ArticleTitle { get; set; }
public string Description { get; set; }
public string Tag { get; set; }
}
}

Now we are going to create Dbcontext class for database connectivity.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace WEBAPI.Models
{
public class AspMantraDBContext :DbContext
{
public AspMantraDBContext() : base("dbconnection") { }
public DbSet<Article> Articles { get; set; }
}
}

 

Now add in interface to project. Right click on interface folder and add an interface.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WEBAPI.Models;
namespace WEBAPI.Interface
{
public interface IArticle : IDisposable
{
IEnumerable<Article> GetArticles();
Article GetArticleById(int id);
void AddArticle(Article item);
void UpdateArticle(Article item,int articleid);
void DeleteArticle(int id);
}
}

 

Add service class in services folder. (ArticleService.cs)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WEBAPI.Interface;
using WEBAPI.Models;


namespace WEBAPI.Services
{
public class ArticleService : IArticle
{
private AspMantraDBContext db = new AspMantraDBContext();
public void AddArticle(Article item)
{

try
{
db.Articles.Add(new Article
{
ArticleTitle = item.ArticleTitle,
Description = item.Description,
Tag = item.Tag
});
db.SaveChanges();
}
catch(Exception ex) { throw ex; }
}


public void DeleteArticle(int id)
{
try
{
Article article = db.Articles.Find(id);
if (article != null)
{
db.Articles.Remove(article);
db.SaveChanges();
}
}
catch(Exception ex)
{
throw ex;
}
}


public Article GetArticleById(int id)
{
var getarticle = db.Articles.Where(x=>x.ArticleId== id).FirstOrDefault();
return getarticle;
}


public IEnumerable<Article> GetArticles()
{
var getarticle = db.Articles.ToList();
return getarticle;
}


public void UpdateArticle(Article item, int articleid)
{
var article = db.Articles.Where(x => x.ArticleId == articleid).FirstOrDefault();
try
{
if(article != null)
{
article.ArticleTitle = item.ArticleTitle;
article.Description = item.Description;
article.Tag = item.Tag;
db.SaveChanges();
}
}
catch (Exception ex) { throw ex; }
}


#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls

protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}

// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.

// TODO: set large fields to null.
disposedValue = true;
}
}

// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~ArticleService()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }

// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}

  

Add a Web API controller to project.


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WEBAPI.Models;
using WEBAPI.Interface;
namespace WEBAPI.Controllers
{
public class ArticlesController : ApiController
{
private readonly IArticle _article;

public ArticlesController(IArticle article)
{
_article = article;
}


[HttpGet]
public IEnumerable<Article> GetArticles()
{
return _article.GetArticles();
}

[HttpGet] public Article GetArticle(int id) { return _article.GetArticleById(id); }

[HttpPost]
public IHttpActionResult AddArticle(Article article)
{
_article.AddArticle(article);
return Ok(new { message = "Article is added successfully." });
}

[HttpPut]
public IHttpActionResult UpdateArticle(Article article,int articleid)
{
_article.UpdateArticle(article, articleid);
return Ok(new { message = "Article is updated successfully." });
}


[HttpDelete]
public IHttpActionResult DeleteArticle(int id)
{
_article.DeleteArticle(id);
return Ok(new { message = "Article is deleted successfully." });
}
}
}

Register the interface and service in unityconfig.cs


using System.Web.Http;
using Unity;
using Unity.WebApi;
using WEBAPI.Interface;
using WEBAPI.Services;
namespace WEBAPI
{
public static class UnityConfig
{
public static void RegisterComponents()
{

var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IHello, HelloService>();
container.RegisterType<IArticle, ArticleService>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
}

Now enable the migration for project. To enable the migration run the below given command in package manager console.

enable-migrations

After that add the migration. Run the below command to add migration with migration name.

Add-migration migration_name

After that update the database. Run the below given to update the database.

Update-database

 

That’s it. Now build the application and run the project.


  


No comments:

Post a Comment