MVC 5.0奇怪的行为

时间:2015-06-09 13:35:21

标签: c# asp.net-mvc behavior

每次增加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));
}

1 个答案:

答案 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