{"id":16,"date":"2023-05-04T07:08:10","date_gmt":"2023-05-04T06:08:10","guid":{"rendered":"https:\/\/ishooscode.com\/?p=16"},"modified":"2023-06-01T09:12:42","modified_gmt":"2023-06-01T08:12:42","slug":"implementing-repository-with-aspnetcore-mvc","status":"publish","type":"post","link":"https:\/\/ishooscode.com\/index.php\/2023\/05\/04\/implementing-repository-with-aspnetcore-mvc\/","title":{"rendered":"Implementing Repository with AspNetCore MVC"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Icon.png\" alt=\"\" class=\"wp-image-17\" width=\"839\" height=\"470\"\/><\/figure>\n\n\n\n<p>In this blog I will create an application using .net Core MVC and Entity framework core implementing Repository pattern and Dependency Injection.<br>I will make the application loosely coupled as much as possible. Data access layer and UI will be completely independent of each other.<\/p>\n\n\n\n<p><strong>Prerequisite<\/strong><\/p>\n\n\n\n<p>Prior knowledge of MVC and Entity framework<\/p>\n\n\n\n<p>Let\u2019s begin<\/p>\n\n\n\n<p><strong>Project Creation<\/strong><\/p>\n\n\n\n<p>I am using visual studio 2019 community edition.<br>Open your IDE and create .net core MVC project<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"360\" height=\"93\" src=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/CreateNew.png\" alt=\"\" class=\"wp-image-19\" srcset=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/CreateNew.png 360w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/CreateNew-300x78.png 300w\" sizes=\"(max-width: 360px) 100vw, 360px\" \/><\/figure>\n\n\n\n<p>Select Asp.Net Core Web Application and press next<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"511\" height=\"117\" src=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/NewCorProject.png\" alt=\"\" class=\"wp-image-20\" srcset=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/NewCorProject.png 511w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/NewCorProject-300x69.png 300w\" sizes=\"(max-width: 511px) 100vw, 511px\" \/><\/figure>\n\n\n\n<p>Name your solution and create<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"944\" height=\"610\" src=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Create.png\" alt=\"\" class=\"wp-image-21\" srcset=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Create.png 944w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Create-300x194.png 300w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Create-768x496.png 768w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Create-850x549.png 850w\" sizes=\"(max-width: 944px) 100vw, 944px\" \/><\/figure>\n\n\n\n<p>Project is created<\/p>\n\n\n\n<p>The solution will have Controller, Model, View folder and one new wwwroot folder and few more files named appsetting.json, Startup.cs, Program.cs<\/p>\n\n\n\n<p>Let\u2019s understand what these files are?<\/p>\n\n\n\n<p>Appsetting.json file is your web.config file<br>Program.cs file is same as in your console application and is called once for the entire application life cycle<br>Startup.cs is used for configuring your .net core application<\/p>\n\n\n\n<p>Let us create a small module of adding product in Ecommerce website<\/p>\n\n\n\n<p><strong>Model<\/strong><\/p>\n\n\n\n<p>First create a Product model in, for that we will create a new .net core class library project in same solution<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>namespace ECommerce.Entity\n{\n&nbsp;&nbsp;&nbsp; &#91;Table(\"Product\")]\n&nbsp;&nbsp;&nbsp; public class Product\n&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;Key]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string ProductId { get; set;&nbsp; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;Required]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;MaxLength(50)]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string ProductName { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;MaxLength(300)]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string ProductDescription { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;Required]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;DisplayName(\"Category\")]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string CategoryId { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;Required]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double QuantityPerUnit { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;Required]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double UnitPrice { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;Required]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double MSRP { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double AvailableSize { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string AvailableColor { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double Discount { get; set; }\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;Required]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double UnitWeight { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#91;Required]\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double UnitsInStock { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double UnitsOnOrder { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public double ProductAvailability { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string Picture { get; set; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public string Note { get; set; }\n&nbsp;&nbsp;&nbsp; }\n}<\/code><\/pre>\n\n\n\n<p>This model will be used to save data and bind view and controller.<\/p>\n\n\n\n<p><strong>Entity framework core Context<\/strong><\/p>\n\n\n\n<p>Next step is to create Entity framework core context. For that we create a new .net core class library project and install a nugget package in it.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"655\" height=\"74\" src=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/EntityframeworkCore.png\" alt=\"\" class=\"wp-image-22\" srcset=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/EntityframeworkCore.png 655w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/EntityframeworkCore-300x34.png 300w\" sizes=\"(max-width: 655px) 100vw, 655px\" \/><\/figure>\n\n\n\n<p>Create a ECommerceContext class<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class ECommerceContext : DbContext\n&nbsp;&nbsp;&nbsp; {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public ECommerceContext(DbContextOptions&lt;ECommerceContext&gt; options) : base(options)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public DbSet&lt;Product&gt; Products { get; set; }\n&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<p><strong>Repository<\/strong><\/p>\n\n\n\n<p>Now let\u2019s create a new .net core class library project named Ecommerce.IRepositories<\/p>\n\n\n\n<p>And create an interface in the project. This project will only contain Interfaces<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public interface IProductRepository\n{\n&nbsp;&nbsp;&nbsp; IList&lt;Product&gt; GetProducts();\n&nbsp;&nbsp;&nbsp; Product GetProduct(string productId);\n&nbsp;&nbsp;&nbsp; void Add(Product product);\n&nbsp;&nbsp;&nbsp; Product Update(Product product);\n&nbsp;&nbsp;&nbsp; void Delete(Product product);\n}<\/code><\/pre>\n\n\n\n<p>Interfaces plays key roles in making application loosely coupled and more injectable more<\/p>\n\n\n\n<p>To implement this interface we\u2019ll create another .net core class library project for repository<\/p>\n\n\n\n<p>Name Ecommerce.Repositories and create a class<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class ProductRepository : IProductRepository\n{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private readonly ECommerceContext productContext;\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public ProductRepository(ECommerceContext context)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; productContext = context;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void Add(Product product)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; product.ProductId = Guid.NewGuid().ToString();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; productContext.Add(product);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; productContext.SaveChanges();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public void Delete(Product product)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; productContext.Products.Remove(product);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; productContext.SaveChanges();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public IList&lt;Product&gt; GetProducts()\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return productContext.Products.ToList();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public Product GetProduct(string productId)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return productContext.Products.FirstOrDefault(x=&gt; x.ProductId == productId);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public Product Update(Product productChanges)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var product = productContext.Products.Attach(productChanges);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; product.State = Microsoft.EntityFrameworkCore.EntityState.Modified;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; productContext.SaveChanges();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return productChanges;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<p>Now, we have created our context, our model and our repository.<\/p>\n\n\n\n<p><strong>Application<\/strong><\/p>\n\n\n\n<p>It\u2019s time to create controller named ProductController.cs and inject all the dependency in it. To inject the dependencies we need to configure startup.cs file<\/p>\n\n\n\n<p>Add following code in ConfigureService method<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>services.AddScoped&lt;IProductRepository, ProductRepository&gt;();\nservices.AddDbContextPool&lt;ECommerceContext&gt;(x =&gt; x.UseSqlServer(ConnectionString, b =&gt; b.MigrationsAssembly(\"ECommerce\")));<\/code><\/pre>\n\n\n\n<p>controller will look like below code<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>IProductRepository productRepo = null;\n\npublic ProductController(IProductRepository prodRepo)\n{\n    productRepo = prodRepo;\n}<\/code><\/pre>\n\n\n\n<p>As you can see we are using parameterized constructor of controller to inject the dependency.<\/p>\n\n\n\n<p>.net core there is a build in support for dependency injection<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>services.AddScoped&lt;IProductRepository, ProductRepository&gt;();<\/code><\/pre>\n\n\n\n<p>Above line is used to inject any dependency in controller<\/p>\n\n\n\n<p>Below method is used to save Product detail in database<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public ActionResult SaveProduct(Product product)\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int res = 3;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (ModelState.IsValid)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (string.IsNullOrEmpty(product.ProductId))\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; productRepo.Add(product);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; product = productRepo.Update(product);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; res = 1;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else {\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return View(\"Create\");\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<p>View to controller binding is same as it was in MVC application and I understand you guys are better at that so not going through with it<\/p>\n\n\n\n<p><strong>Notes<\/strong><\/p>\n\n\n\n<p>If you look at the Repository class, I have injected context class in its constructor.<\/p>\n\n\n\n<p><strong>Summary<\/strong><\/p>\n\n\n\n<p>This is how you create a .net core MVC application with Repository and dependency injection which is loosely coupled and easily configurable<\/p>\n\n\n\n<p>I am open to all kind of discussion. Feel free to comment and suggest anything<\/p>\n\n\n\n<p>For more details please <a href=\"https:\/\/www.c-sharpcorner.com\/members\/ishoo-agarwal\" target=\"_blank\" rel=\"noopener\" title=\"visit \">visit <\/a><\/p>\n\n\n\n<p>Thank you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this blog I will create an application using .net Core MVC and Entity framework&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[23,22],"tags":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/16"}],"collection":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/comments?post=16"}],"version-history":[{"count":8,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/16\/revisions"}],"predecessor-version":[{"id":60,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/16\/revisions\/60"}],"wp:attachment":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/media?parent=16"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/categories?post=16"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/tags?post=16"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}