locked
Avoiding code repetition RRS feed

  • Question

  • User-81839486 posted

    I want to create small servis where I have few databases. For every databases I have to create page with adding new row and showing table. How can I avoid code repetition? I am afraid some code will be reapeated with minor changes especially with sql queries with parameters.

    Thursday, August 13, 2020 10:41 PM

All replies

  • User1120430333 posted

    Maybe the link will help you. However, you need to explain what code logic  with example that you think will be DRY situations for you. 

    https://docs.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/architectural-principles

    Friday, August 14, 2020 12:11 AM
  • User711641945 posted

    Hi karol,

    I think you could try to use Generic Repository to avoid code repetion.

    Here is a sample:

    public class BaseController<T>:Controller where T:class
    {
        private readonly MyDbContext _context;
        public BaseController(MyDbContext context)
        {
            _context = context;
        }
        public async Task<IActionResult> Index()
        {
            return View(await _context.Set<T>().ToListAsync());
        }
    
        // GET: Tests/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
    
            var test = await _context.Set<T>()
                .FindAsync(id);
            if (test == null)
            {
                return NotFound();
            }
    
            return View(test);
        }
    
        // GET: Tests/Create
        public IActionResult Create()
        {
            return View();
        }
    
        // POST: Tests/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult<T>> Create(T test)
        {
            if (ModelState.IsValid)
            {
                _context.Add(test);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(test);
        }
    //..... }

    And you just need create a controller which inherits the BaseController and pass the model you want.No need to write the same code for several times:

    public class TestsController : BaseController<Test>
    {
        private readonly MyDbContext _context;
    
        public TestsController(MyDbContext context):base(context)
        {
            _context = context;
        }
    }

    Best Regards,

    Rena

    Friday, August 14, 2020 9:38 AM