我正在尝试创建投票/投票申请,并希望跟踪为这些选项所做的投票数量。进行投票时,传入一个id并根据id - 计数器增加一。但是当我投票时,它将另一个计数器设置为一个。
// ID of the option selected:
public int VotedID { get; set; }
Counters for the options:
public int BlueCornerPercent { get; set; }
public int RedCornerPercent { get; set; }
// Snippet of code - here is where I increase the counters. theFight is an instance of the model/entity.
public void HandleVotes(Fight fight)
{
// Get full fight details:
Fight theFight = db.Fights.Find(fight.FightId);
// Get fighters id's in fight:
var f1 = (from l in theFight.Fighters
select l).First();
var f2 = (from l in theFight.Fighters
select l).Last();
if (theFight.VotedID == f1.FighterID)
{
theFight.BlueCornerPercent++;
db.SaveChanges();
}
else if (theFight.VotedID == f2.FighterID)
{
theFight.RedCornerPercent++;
db.SaveChanges();
}
}
如我所见,我正在通过正在投票的“战斗”并从那里更换柜台......
答案 0 :(得分:1)
您可以尝试使用以下内容:
if (theFight.VotedID == f1.FighterID)
{
theFight.BlueCornerPercent++;
db.Entry(theFight).Property(p => p.BlueCornerPercent).IsModified = true;
db.Entry(theFight).Property(p => p.RedCornerPercent).IsModified = false;
db.SaveChanges();
}
答案 1 :(得分:0)
我找到了解决方案,我需要在视图中包含计数器的隐藏属性,以防止它们重置。