C# ASP.NET API Post with 2 primary-keys

I want to use post in a Table where there is 2 primary-keys, and I wanted to do it only using one one of these keys, in that case “classifies.cod_prova”.
here is the code I’ve right now:

 [HttpPost]
        public string Post([FromBody] Classifics classifics)
        {
            using (var db = new Dbhelper())
            {
                if (db.classifics.Find(classifics.cod_prova,classifics.cod_cavalo) == null)
                {
                    db.classifics.Add(classifics);
                    db.SaveChanges();
                    return "OK";
                }
                else { return "already exists"; }
            }
        }```

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I think you’re trying to add a record only if one of the parts of the composite keys doesn’t exist in the table for any record. You can’t use the Find() method to search for a record that has a composite (2 or more fields) key in the DB using a single field. You could use the .Where() and .Any() methods to find if there are records that contain the one field you’re looking for (classifics.cod_prova)

        // This will return true if there are no records that contain the same 
        // value for cod_prova
        if (!db.classifics.Where(c => c.cod_prova == classifics.cod_prova).Any())
        {

            db.classifics.Add(classifics);
            db.SaveChanges();
            return "OK";

        }
        else { return "already exists"; }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x