我有一個公告頁面,當用戶查看它時,將它添加到「看到」數據庫中。這個問題是,如果我用戶然後點擊兩次相同的頁面然後記錄兩次,等等。這裏是我的代碼,我如何檢查數據庫中是否存在該條目?防止重複插入到數據庫中
public ActionResult Index()
{
string currentUserId = User.Identity.GetUserId();
var currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
List<Seen> seens = new List<Seen>();
foreach (Announcement anoun in db.Announcements)
{
seens.Add(new Seen
{
User = currentUser, // You have this already so why go to the database again?
Announcement = anoun, // Same with this.
});
}
db.Seens.AddRange(seens);
db.SaveChanges();
return View(db.Announcements.ToList());
}
你只需要添加到數據庫,在這裏是檢查你的代碼,如果它已經存在的數據庫? –
@ L.B多數民衆贊成在什麼問題是 – user3042332
所以你想有人爲你寫嗎?你的努力在哪裏? –