[英]Save and Edit to DataBase(Entity Framework)
I have Like button, when it pressed - controller action should add field to my dbTable("Likes"), and if button pressed again - it should remove Like from dbTable("Likes"). 我有“赞”按钮,当它按下时-控制器动作应将字段添加到我的dbTable(“ Likes”)中,如果再次按下该按钮,则应从dbTable(“ Likes”)中删除“赞”。
Here code(simplified): 这里的代码(简体):
var like = db.Likes.Find(id);
if (like == null)
{
Like like = new Like("SomeData", UserPosedLike);
db.Add(like);
}
else
{
db.Likes.Remove(like);
}
db.SaveChanges();
It's work fine at 95% of times, but if i press button very fast 2-3 times, it throws error – “Null ref”, some data in Like is NULL (but this data can't be null, because it references to other dbField(User)). 在95%的时间它可以正常工作,但是如果我非常快地按下按钮2-3次,则会引发错误-“ Null ref”,Like中的某些数据为NULL(但是此数据不能为null,因为它引用了其他dbField(User))。 Also, sometimes it adds two likes, but it shouldn't. 此外,有时还会添加两个赞,但不应添加。
I think it happens because of: 我认为这是因为:
First action(press) – read db, start processing. 第一步(按)–读取db,开始处理。
Second action (second press) – read db, start processing. 第二步(第二次按下)–读取db,开始处理。 (first action not saved data yet). (第一个动作尚未保存数据)。
First action(press) – save data. 第一步(按)–保存数据。
Second action(pess) – save data. 第二动作(pess)–保存数据。
Here we got 2 likes. 在这里,我们有2个赞。 Probably with “null error” similar problem. 可能与“空错误”类似的问题。
I received advice to lock this block of code, but I think it's wrong. 我收到了有关锁定此代码块的建议,但我认为这是错误的。 Also I thinking about Optimistic Concurrency, currently reading about it. 我也在考虑乐观并发性,目前正在阅读有关它。
I'm not good with db, any help will be great - good book, code, article or advice. 我对db不好,任何帮助都会很棒-好书,代码,文章或建议。 Thank you! 谢谢!
You need to read and write in transaction . 你需要阅读和写 交易 。
using (var db = new YourContext())
{
using (var t = db.Database.BeginTransaction())
{
try
{
var like = db.Likes.Find(id);
if (like == null)
{
Like like = new Like("SomeData", UserPosedLike);
db.Add(like);
}
else
{
db.Likes.Remove(like);
}
db.SaveChanges();
t.Commit();
}
catch
{
t.Rollback();
}
}
}
I received advice to lock this block of code, but I think it's wrong. 我收到了有关锁定此代码块的建议,但我认为这是错误的。
It is wrong. 这是错误的。
Also as someone has suggested in comments, you can prevent users from clicking a button multiple times. 同样,正如有人在评论中建议的那样,您可以防止用户多次单击按钮。 You could disable the button and add a spinner. 您可以禁用该按钮并添加一个微调器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.