MVC 5.0 strange behavior

82 views Asked by At

When I run this action every time it increases rating.Likes. Can I have a little help?

public ActionResult Like(int id)
{
    ApplicationDbContext db = new ApplicationDbContext();
    var rating = db.Ratings.FirstOrDefault(x => x.id == id);

    if (!(rating.RatedFrom.Contains(User.Identity.Name)))
    {
        rating.Likes++;
        rating.RatedFrom.Add(User.Identity.Name); 
    }

    rating.Views--;
    db.SaveChanges();
    return RedirectToAction("Details", db.ImageModels.FirstOrDefault(x => x.id == id));
}
1

There are 1 answers

0
Fals On BEST ANSWER

1) Create the RatedFrom class:

public class RatedFrom
{
    public int Id {get; set;}
    public string UserName {get; set;}
    public DateTime RatedDate {get; set;}
    /*Other properties*/
}

2) Setup the RatedFrom at your Ratings

public class Rating 
{
    /*Other properties*/

    public virtual ICollection<RatedFrom> RatedFromList {get; set;}

    public Rating()
    {
        /*Other properties initialization*/
        RatedFromList = new List<RatedFrom>();
    }
}

3) Setup the RatedFrom at you DbContext to be mapped to the Data Base:

public DbSet<RatedFrom> RatedFrom { get; set; }

4) Change the Controller code:

if (!(rating.RatedFromList.Where(x=> x.UserName == User.Identity.Name).Count() > 0))
{
    rating.Likes++;
    rating.RatedFrom.Add(new RatedFrom {  UserName = User.Identity.Name }); 
}

And done! Given that you are using Coding-First. If you are using Database-first you must create the class mapp manually: Mapping to Existing Table in the Database