简体   繁体   English

带有 2 个主键的 C# ASP.NET API Post

[英]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".我想在有 2 个主键的表中使用 post,并且我只想使用这些键之一来完成它,在这种情况下是“classifying.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"; }
            }
        }```

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.您不能使用 Find() 方法在数据库中使用单个字段搜索具有复合(2 个或更多字段)键的记录。 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)您可以使用 .Where() 和 .Any() 方法来查找是否有包含您要查找的字段的记录 (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"; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM