每次增加rating.Likes
时我都会执行此操作。
我可以帮忙吗?
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));
}
答案 0 :(得分:0)
1)创建RatedFrom
类:
public class RatedFrom
{
public int Id {get; set;}
public string UserName {get; set;}
public DateTime RatedDate {get; set;}
/*Other properties*/
}
2)在RatedFrom
Ratings
public class Rating
{
/*Other properties*/
public virtual ICollection<RatedFrom> RatedFromList {get; set;}
public Rating()
{
/*Other properties initialization*/
RatedFromList = new List<RatedFrom>();
}
}
3)设置您RatedFrom
DbContext
以映射到数据库:
public DbSet<RatedFrom> RatedFrom { get; set; }
4)更改控制器代码:
if (!(rating.RatedFromList.Where(x=> x.UserName == User.Identity.Name).Count() > 0))
{
rating.Likes++;
rating.RatedFrom.Add(new RatedFrom { UserName = User.Identity.Name });
}
完成了!鉴于您使用的是Coding-First。如果您使用的是数据库优先,则必须手动创建类mapp:Mapping to Existing Table in the Database