I have a page of announcements that when a user views it, adds it to a "seen" database. The issue with this is, if I user then clicks the same page twice then it records that twice and so on. Here is my code, How could I check if the entry already exists in the database?
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());
}