将 C# 变量设置为 SQL 中自动递增的列值的值?

Setting a C# variable to the value of an auto-incremented column value in SQL?

好吧,我正在做一个模拟停车场售票机的项目。我必须能够让用户打卡,给他们分配一张票,然后让他们使用这张票打卡,并根据在停车场的时间向他们收费。我将他们的数据插入到具有自动递增 ID 列的 table 中,因为我需要能够跟踪他们是哪张票,并相应地 add/remove 他们。我 运行 使用此代码将他们的票添加到数据库并且运行良好,我 运行 在获取数据库提供的票并将其分配给任务所需的票对象时遇到了一些麻烦我们使用。这是他们打卡时我使用的代码。

    private void EnterBtn_Click(object sender, EventArgs e)
    {

        DateTime timeIn = new DateTime();
        timeIn = DateTime.Now;
        int ticketID = 0;

        MessageBox.Show("Entered Parking Garage at: " + timeIn.ToString());

        //Insert Data into the table, increment the ticketID, store that as the TicketNumber 
        //in the ticket object
        string sqlQuery = "INSERT INTO Tickets (TimeIssued)";
        sqlQuery += "VALUES (@TimeIssued)";
        using (SqlConnection dataConnection = new SqlConnection("Data Source=stusql.otc.edu;Initial Catalog=th0732193;Integrated Security=True"))
        {
            using (SqlCommand dataCommand = dataConnection.CreateCommand())
            {
                dataConnection.Open();
                dataCommand.CommandType = CommandType.Text;
                dataCommand.CommandText = sqlQuery;
                dataCommand.Parameters.AddWithValue("@TimeIssued", timeIn);
                dataCommand.ExecuteNonQuery();
                ticketID = Convert.ToInt32(dataCommand.Parameters["@TicketID"].Value.ToString());
                dataConnection.Close();

            }
        }

        Ticket newTicket = new Ticket();
        newTicket.TimeIn = timeIn;
        newTicket.TicketNumber = ticketID;
    }

所以主要问题是因为列是自动递增的,所以我不能添加参数,否则它会把它搞砸(除非有一种我不知道的方法,如果所以,太棒了!),这是个问题,因为我需要将该票证 ID 分配给票证对象。

我的问题是,如何将存储在数据库中的 TicketID 设置为 Ticket 对象中的代码 属性。

我找遍了,但找不到对我的具体情况有帮助的这个问题的解决方案,所以尽管我确定这是一个愚蠢的问题,但我确实需要一些帮助,我将不胜感激它!

将它添加到 dataCommand.ExecuteNonQuery 行之后是否有效?

dataCommand.CommandText = "SELECT @@IDENTITY";
int id = dataCommand.ExecuteScalar();

更改 sql 查询如下

string sqlQuery ="INSERT INTO Tickets (TimeIssued) OUTPUT INSERTED.TicketID VALUES(@TimeIssued)

然后

dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.AddWithValue("@TimeIssued", timeIn);
 int TicketID = (int) dataCommand.ExecuteScalar();