0
[HttpPost]
public void InsertOrUpdateDirector(Director director)
{
    int idReturned = 0;

    string query = null;
    myConnection.Open();
    if (director.Operation == 'I')
    {
      query = "INSERT...";
    }
    else if (director.Operation == 'U')
    {
      query = "UPDATE ...";
    }
    var cmd = new SqlCommand(query, myConnection);
    cmd.ExecuteNonQuery();
    myConnection.Close();

    idReturned = "???";

    return idReturned;
}

我只是想在插入语句之后返回新创建的 ID。我该怎么做呢?

4

2 回答 2

6

SELECT SCOPE_IDENTITY()在插入后添加到您的查询中。并打电话

idReturned = cmd.ExecuteScalar();

代替cmd.ExecuteNonQuery()

然后检查 idReturned 是否为 null,cmd.ExecuteScalar() 将为您的更新查询返回 null,主键应该是 Director 对象的一方,因此您可以执行以下操作:

if(idReturned == null){
    return director.DirectorId //just guessing at name of id property here for example sake
}else{
    return idReturned;
}

您应该已经将主键传递给 InsertOrUpdateDirector 以编写更新查询。

于 2013-09-11T23:16:59.500 回答
0
 Try this code,I hope this will work
myConnection.Open();
    if (director.Operation == 'I')
        {
          query = "INSERT...";
    string query1="select  createdId  from table";

        }
    var cmd = new SqlCommand(query, myConnection);
    Sqlcommand cmd1=new SqlCommand(query1,myConnection);
        cmd.ExecuteNonQuery();
    int CreatedId=cmd1.ExecuteScalar();
    return  CreatedId;
        myConnection.Close();
     myConnection.Close();
于 2013-09-12T05:23:26.357 回答