Home > Mobile >  How to create Delete method for Repository and Controller>
How to create Delete method for Repository and Controller>

Time:01-16

This is my Interface

 public interface ISuperHeroRepo
    {

        Task<List<SuperHero>> GetAll();
        Task<SuperHero> GetById(int id);
        Task<SuperHero> Create(SuperHero superHero);
        Task<SuperHero> Update(SuperHero superHero);
        void Delete(int id);
     }

This is my Repository

  public class SuperHeroRepo : ISuperHeroRepo
    {
        private readonly DataContext _ctx;

        public SuperHeroRepo(DataContext ctx)
        {
            _ctx = ctx;
        }




        public void Delete(int id)
        {
            //Cann't Implement
            throw new NotImplementedException();
        }

    }

This is my Controller

 [Route("api/[controller]")]
    [ApiController]
    public class SuperHeroController : ControllerBase
    {
        private readonly ISuperHeroRepo _context;

        public SuperHeroController(ISuperHeroRepo context)
        {
            _context = context;
        }


       
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
           
            //cannt implement
        }




    }

I use Repository pattern. I want CURD operation. I already implement code for Create, update, and Get method. But I cant implement code for repository and Interface For Delete method. Any one please help. [I am beginner]

CodePudding user response:

I suggest you read the following article. https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-6.0

I will also complete the code for you.

 public interface ISuperHeroRepo
    {
        Task<List<SuperHero>> GetAll();
        Task<SuperHero> GetById(int id);
        Task<SuperHero> Create(SuperHero superHero);
        Task<SuperHero> Update(SuperHero superHero);
        void Delete(SuperHero superHero);
        Task SaveChangesAsync();
     }

Controller :

   [Route("api/[controller]")]
[ApiController]
public class SuperHeroController : ControllerBase
{
    private readonly ISuperHeroRepo _context;

    public SuperHeroController(ISuperHeroRepo context)
    {
        _context = context;
    }


   
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
       var result  = await _context.GetById (id)
       _context.Delete(result);
       await _context.SaveChangesAsync();
    }
}

CodePudding user response:

Instead of fetching a SuperHero just to delete it, use a stub entity.

    public void Delete(int id)
    {
        var e = new SuperHero() {Id = id};
        _ctx.Set<SuperHero>().Remove(e);
    }
  •  Tags:  
  • Related