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?

3
  • Is there a default constructor for TimeSlipsTableAdapter defined somewhere else? Commented Jun 26, 2021 at 2:52
  • See also closely related stackoverflow.com/questions/9371200/… (it'd be a duplicate, except it's really more specific to a T4-related scenario) Commented Jun 26, 2021 at 4:57
  • @DStanley Yes, sorry. The default constructor is in the auto-generated code the DataSet Designer produces. Commented Jun 26, 2021 at 14:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.