Getting concurrency error on updating record with data adapter

前端 未结 2 900
生来不讨喜
生来不讨喜 2021-01-17 05:40

This is my table:

Student:StudentId int PK autoincrement,Name varchar(20)

When i am trying to update last added records then i

2条回答
  •  心在旅途
    2021-01-17 06:03

    As described in the Generating Commands with CommandBuilders MSDN topic, the automatic commands generated by the command builders do not retrieve the identity fields for the inserted records:

    You might want to map output parameters back to the updated row of a DataSet. One common task would be retrieving the value of an automatically generated identity field or time stamp from the data source. The DbCommandBuilder will not map output parameters to columns in an updated row by default. In this instance you must specify your command explicitly.

    Looking at Retrieving Identity or Autonumber Values topic, it turns out that basically you need to generate the insert command manually.

    Here is how you can do that for your table (see the comments inside the code):

    using (var connection = new SqlConnection("MyConnectionstring"))
    {
        connection.Open();
    
        // Create data adapter with the specified SelectCommand
        var adapter = new SqlDataAdapter("select * from Student", connection);
    
        // Build InsertCommand    
        var insertCommand = new SqlCommand(
            "insert into Student (Name) values (@Name) SET @Id = SCOPE_IDENTITY()", 
            connection);
        insertCommand.Parameters.Add("@Name", SqlDbType.VarChar, 20, "Name");
        var parameter = insertCommand.Parameters.Add("@Id", SqlDbType.Int, 0, "StudentId");
        parameter.Direction = ParameterDirection.Output;
        insertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;
        adapter.InsertCommand = insertCommand;
    
        // Auto build outher commands
        var builder = new SqlCommandBuilder(adapter);
    
        // Read the data
        var dt = new DataTable();
        adapter.Fill(dt);
    
        // Insert a new record
        var row = dt.NewRow();
        row["Name"] = "Abc";
        dt.Rows.Add(row);
    
        adapter.Update(dt);
    
        // Update the just inserted record
        row["Name"] = "Pqr";
        adapter.Update(dt);
    
        connection.Close();
    }  
    

提交回复
热议问题