wsduho wsduho - 8 months ago 49
C# Question

Invoking specific methods based on Specific Constructor

I want to both save new records and update existing records using a single form
but with two constructors (one with parameters and the other without). The constructor that is called should determine which method should be invoked(Save or Update).

public ManageRecord(Record record ){ //update record }

public ManageRecord(){ //save new record }

private void Save_Click(object sender, RoutedEventArgs e){
//if default constructor invokes form call save method
//if constructor with parameters invokes form call update method

How do i achieve this?


What I've done in the past to solve this is to have the Primary Key field on the Model as a Nullable field. When you try to save the record you can just look at the field on the Model, if MyPk.HasValue returns true, then you are updating a record, if it is false, you are inserting a new record.

When you call the constructor that takes an instance of model, just save it in a local field. When the constructor without a model is called, create a new model instance with a null PK, and save it in the local field. Save can just examine the local field.

So in the end, your action isn't directly based on which constructor was called, it should be based on the state of the model that you are currently working with.