Here are the steps to create the Category repository class in the NorthwindCafe application:
1. Create the ICategoryRepository interface for dependency injection, create a file call ICategoryRepository.cs in the "Models" folder with the following code
using System.Collections.Generic; namespace NorthwindCafe.Web.Models { public interface ICategoryRepository { IEnumerableGetAllCategories(); Category GetCategory(int Id); } }
2. Create the CategoryRepository.cs implementation class and save it in the "Models" folder
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NorthwindCafe.Web.Models { public class CategoryRepository : ICategoryRepository { private NorthwindContext _context; public CategoryRepository(NorthwindContext context) { _context = context; } public IEnumerableGetAllCategories() { return _context.Categories.ToList(); } public Category GetCategory(int Id) { return _context.Categories.Where(c => c.Id == Id).FirstOrDefault(); } } }
This class basically encapsulate the retrieval methods of the Entity Framework methods. By using the repository pattern the developer calling the method does not care how the data is retrieved they just know that it is retrieving the correct data.
3. Now open the Startup.cs file and type in the following lines of code to add the CategoryRepository class object in the ConfigureServices method services.AddScoped
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var connectionString = Startup.Configuration["Data:NorthwindContextConnection"]; services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(connectionString)); services.AddScoped<ICategoryRepository, CategoryRepository>(); services.AddLogging(); }
4. Now to use it in our HomeController all we have to do is inject it into the constructor
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NorthwindCafe.Web.Models; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace NorthwindCafe.Web.Controllers { public class HomeController : Controller { private ICategoryRepository _categoryRepo; private ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger, ICategoryRepository categoryRepo) { _logger = logger; _categoryRepo = categoryRepo; } // GET: /<controller>/ public IActionResult Index() { var categories = _categoryRepo.GetAllCategories(); return View(); } } }
If you run the application in debug mode you will see that the Categories have been retrieved from the database using the GetAllCategories method
This comment has been removed by the author.
ReplyDeleteAivivu đại lý vé máy bay, tham khảo
ReplyDeletevé máy bay đi Mỹ bao nhiêu tiền
chuyến bay từ mỹ về việt nam tháng 1/2021
các đường bay từ canada về việt nam
vé từ nhật về việt nam
giá vé máy bay từ hàn quốc về việt nam
Vé máy bay từ Đài Loan về Việt Nam
chuyến bay chuyên gia trung quốc