Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

how to add and delete favorites in asp.net core api

I develop a news application with ASP.net API. I want users to be able to add and deleted their favorites articles. I created a Favorites model like this:

public class Favorites{

   public String userId {get; set;}
   public UserEntity User {get; set;}
   public int articleId {get; set; }
   public virtual Article article {get; set;}

}

I initialized it with dotnet fluentapi:

modelBuilder.Entity<Favorites>().HasKey(a => new{ a.articleId, a.userId }); 

this is how the controller looks like :

 public class FavoritesController : ControllerBase
    {
        private readonly DatabaseContext _context;

        public FavoritesController(DatabaseContext context)
        {
            _context = context;

            _context.Database.EnsureCreated(); 
        }

        // GET: api/Favorites
        [HttpGet(Name = nameof(GetAllFavorites))]
        public async Task<ActionResult<IEnumerable<FavoriteDTo>>> GetAllFavorites( [FromQuery] NewRoomQueryParameters queryParameter)
        {
            IQueryable<Favorites> favs = _context.Favorites;

            if (!string.IsNullOrEmpty(queryParameter.sortBy))
            {
                if (typeof(Favorites).GetProperty(queryParameter.sortBy) != null)
                {
                    favs = favs.OrderByCustom(queryParameter.sortBy, queryParameter.SortOrder);
                }
            }

           if (!string.IsNullOrEmpty(queryParameter.userId))
            {
                favs = favs.Where(p => p.userId == queryParameter.userId);
            }

            return await favs.Include(a => a.Article)
                               .ThenInclude(a => a.Author)
                              .Include(a => a.Article)
                                .ThenInclude(a => a.Comments)
                             .Select(x => favoriteToDTo(x)).ToListAsync(); 
        }

        // GET: api/Favorites/5
        [HttpGet("{id}")]
        public async Task<ActionResult<FavoriteDTo>> GetFavorites(int id)
        {
            IQueryable<Favorites> favs = _context.Favorites; 

            var favorites = await favs.Include(x => x.Article).FirstOrDefaultAsync(x => x.articleId == id ) ;

            if (favorites == null)
            {
                return NotFound();
            }

            return favoriteToDTo(favorites);
        }

   
        // POST: api/Favorites
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<FavoriteDTo>> PostFavorites(FavoriteDTo favDTo)
        {
            var fav = new Favorites
            {
                articleId = favDTo.articleId, 
                userId = favDTo.userId
            }; 

            _context.Favorites.Add(fav);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (FavoritesExists(fav.articleId))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtAction(nameof(GetFavorites), new { id = fav.articleId }, fav);
        }

        // DELETE: api/Favorites/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteFavorites(int id)
        {
            var favorites = await _context.Favorites.FindAsync(id);
            if (favorites == null)
            {
                return NotFound();
            }

            _context.Favorites.Remove(favorites);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private static FavoriteDTo favoriteToDTo(Favorites favorites) => new FavoriteDTo
        {
            articleId = favorites.articleId,
            Article = favorites.Article,
            User = favorites.User,
            userId = favorites.userId
        }; 

        private bool FavoritesExists(int id)
        {
            return _context.Favorites.Any(e => e.articleId == id);
        }
    }

I can add Favorites just fine. But I cannot remove them. Can somebody help me out ? if it is not the good way to implement this functionality , please I would like to learn how to do it the right way.

question from:https://stackoverflow.com/questions/65871165/how-to-add-and-delete-favorites-in-asp-net-core-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It depends on How you want to delete the favorite. If you want to delete the Article from Favorite for a user,

[HttpDelete("{id}")]
    public async Task<IActionResult> DeleteFavoritesForUser(int Articleid, string userId)
    {
        var favorites = await _context.Favorites.FindBy(x=>x.UserId ==userId && x=>x.ArticleId ==Articleid);
        if (favorites == null)
        {
            return NotFound();
        }

        _context.Favorites.RemoveRange(favorites);
        await _context.SaveChangesAsync();

        return NoContent();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...