PatrickV
PatrickV

Reputation: 2135

Right place to add general code in Lightswitch

I am developing a Lightswitch 2012 greenfield application. I am very new to Lightswitch, so my approach may be completely wrong.

I have a UserProfile table that provides additional user details and that I am planning to use to query for user data as needed. I want to add a general use method that looks up the appropriate record for the current user. The following code is in-line where one of my screens needs to consume this information:

        UserProfile myProfile;
        {
            var profiles = this.DataWorkspace.ApplicationData.UserProfiles;
            string myDomainId = Application.User.Name;
            myProfile = (from profile in profiles.OfType<UserProfile>()
                         where profile != null && profile.DomainId == myDomainId
                         select profile).FirstOrDefault<UserProfile>();
            if (myProfile == null)
            {
                myProfile = profiles.AddNew();
                myProfile.DomainId = myDomainId;
            }
        }

Right now this code runs in one of the onsave routines in one of my screens. I'd like to refactor this for general use into a GetCurrentUserProfile() method. I first tried putting this in the application, but I got context errors.

Where is the right place to put that method?

Upvotes: 1

Views: 557

Answers (2)

Alberto
Alberto

Reputation: 46

Remember that if you want to do something whith data, you must to pass to the new method the current dataworkspace.

Upvotes: 0

Yann Duran
Yann Duran

Reputation: 3879

I've started to find myself explaining the same thing over & over, as more new people start wanting to use LightSwitch in a more advanced way. This is a great thing to see, so to make it a little easier, I'll be adding little "How To's" to my LightSwitch Central site.

Here's the first one: How Do I Refactor Code That I'm Using In One Of My Screens, So I Can Use It In Other Screens? I hope it helps.

Upvotes: 3

Related Questions