Search code examples
c#visual-studio-lightswitch

How do I Automatically insert a new record into a child table when a new record is added to a parent table in Lightswitch?


I have a Lightswitch Desktop Client application in C#. There is a parent table/entity called Participants and a child table called HouseIncomes. One of the field/properties in HouseIncomes is a string property called CurrentLevel with a choice list of Yes and No. When a new record is created in the Participants parent table, how can one record be added to the child HouseIncomes table with the default of "Yes" in the CurrentLevel field?


Solution

  • Using C#, this should work for your scenario:

    Open up your Data Source, click in "Write Code" and select the Participants_Inserted option. (see image below) enter code similar to this: the naming conventions might be slightly out but I have guessed at what yours may be:

        partial void Participants_Inserted(Participants entity)
        {
            HouseIncome houseIncome = DataWorkspace.YOURDATASOURCE.HouseIncomes.AddNew();
            houseIncome.Participants = entity; //THIS ASSIGNS THE FOREIGN KEY RELATIONSHIP TO ITS PARENT
            houseIncome.CurrentLevel = "Yes"; //FOR STRING
            houseIncome.CurrentLevel = true; //FOR BOOLEAN
        }
    

    This code is inserting your child data, linked to your parent data automatically, and setting the Current Level to your desired value.

    enter image description here

    Hope this helps...