0

I'm using an MS Access database (I know...), so to capture the auto-generated primary key, I'm extending the table adapter class. I took me a while to figure this part out, so if that's your problem, future reader, right-click on your dataset file (*.xsd) and select View Code. This will create a partial class. The GetLastID() method is just a query with SELECT @@IDENTITY. The trick is that it has to be done when the row is updated, without closing and opening a new connection, so the RowUpdated event needs to be handled. Here's the code for that:

namespace TimeTrack.TimeTrackDataSetTableAdapters
{
    public partial class TimeSlipsTableAdapter
    {
        public void CustomSetup()
        {
            Adapter.RowUpdated += Adapter_RowUpdated;
        }

        private void Adapter_RowUpdated(object sender, OleDbRowUpdatedEventArgs e)
        {
            if (e.StatementType == StatementType.Insert && e.Errors == null)
            {
                int lastID = (int)GetLastID();
                e.Row["ID"] = lastID;
                e.Status = UpdateStatus.SkipCurrentRow;
            }
        }
    }
}

My question is: Is there are way to avoid having to call the CustomSetup() method?

I would like for somehow to include the event handler assignment in the construction of the table adapter without having to make an additional call. Is there a way?

RobertSF
  • 488
  • 11
  • 24
  • Is there a default constructor for `TimeSlipsTableAdapter` defined somewhere else? – D Stanley Jun 26 '21 at 02:52
  • See also closely related https://stackoverflow.com/questions/9371200/partial-class-constructors-and-event-handler-registration (it'd be a duplicate, except it's really more specific to a T4-related scenario) – Peter Duniho Jun 26 '21 at 04:57
  • @DStanley Yes, sorry. The default constructor is in the auto-generated code the DataSet Designer produces. – RobertSF Jun 26 '21 at 14:11

1 Answers1

1

I think you've got the optimal solution here. While you can add new constructors (with different signatures), there's no way in C# for partial classes to add additional steps to a constructor. The only way to do this is with a method.

Will Moffat
  • 169
  • 8