UpdateDataSet method

Topics: Data Access Application Block
May 9, 2012 at 2:21 PM

Hi All,

Does the Database.UpdateDataSet () method works if the table is not having any Primary key defined on a cloumn?

Thanks,

Amit

May 10, 2012 at 12:04 AM

Yes, you can specify the update criteria in the updateCommand.

In this example assume that CategoryID is some column (or set of columns) that can uniquely identify a record for update:

    Database db = DatabaseFactory.CreateDatabase();

    DataSet ds = new DataSet();

    string sqlCommand = "SELECT CategoryId, CategoryName FROM Category";
    DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);

    string tableName = "Category";

    // Retrieve the initial data.
    db.LoadDataSet(dbCommand, ds, tableName);

    // Get the table that will be modified.
    DataTable table = ds.Tables[tableName];

    // Modify an existing category name.
    table.Rows[1]["CategoryName"] = "Modified";

    DbCommand updateCommand = db.GetSqlStringCommand("UPDATE Category SET CategoryName = @CategoryName WHERE CategoryId = @CategoryId");

    db.AddInParameter(updateCommand, "@CategoryID", DbType.Int32, "CategoryID", DataRowVersion.Current);
    db.AddInParameter(updateCommand, "@CategoryName", DbType.String, "CategoryName", DataRowVersion.Current);

    // Submit the DataSet, capturing the number of rows that were affected.
    int rowsAffected = db.UpdateDataSet(ds, 
        tableName,
        null,
        updateCommand, 
        null,
        UpdateBehavior.Standard);

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com