Try to search your question here, if you can't find : Ask Any Question Now ?

How to check in the controller if a database contains an entry that has duplicate values before adding a new entry?

HomeCategory: stackoverflowHow to check in the controller if a database contains an entry that has duplicate values before adding a new entry?
Avatarcraig asked 2 weeks ago

In the create method for my controller, I need to do a check before actually adding the object to the database. All I need to do is check if there is already an entry that has duplicate values for two of the attributes.

My current idea is to do a sql query to select all entries where those 2 values match the 2 of the current object, and if the count of this query is => 1, then just not adding the object to the database.

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "id,name,winner,points,postDate")] Pick pick)
        {
            SqlConnection con = new SqlConnection();
            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Picks WHERE [score] = @score AND [winner] = @winner", con);

            if (ModelState.IsValid && cmd.value == 0) //I know this is wrong but something like this
            {
                db.Picks.Add(pick);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(pick);
        }

The main thing I need to know are:

  1. Where I put “Picks” in the query, is that the DB name or table name?
  2. In the query, is “[score]” the correct way to write the attribute from a db, and is “@score” the correct way to refer to the value of the attribute of the object you are currently working with?
  3. What would be the method of getting the amount of entries that the query returned?
1 Answers
Best Answer
AvatarAmit answered 2 weeks ago
Your Answer

0 + 6 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com