LINQ RETURNING A SET OF RESULTS

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
 918  View(s)
Ratings:
Rate this:

i have some code that sets user's properties like so:

us = new UserSession();

us.EmailAddr = emailAddr;

us.FullName = fullName;

us.UserROB = GetUserROB(uprUserName);

us.UserID = GetUserID(uprUserName);

us.UserActive = GetUserActive(uprUserName);

where GetUserROB, GetUserID and GetUserActive all look similar like so:

private static string GetUserActive(string userName)

{

    using (Entities ctx = CommonSERT.GetContext())

    {

        var result = (from ur in ctx.datUserRoles

                       where ur.AccountName.Equals(userName, StringComparison.CurrentCultureIgnoreCase)

                       select new

                       {

                           Active = ur.active

                       }).FirstOrDefault();

        if (result != null)

           return result.Active;

        else

           return "N";

     }

  }

it works, but i dont think it's the right way here. how can i assign userROB, ID and Active properties all in one LINQ call? without having to have 3 separate functions to do this?

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: LINQ Returning a set of results

    try this:


    private static void GetUserData(string userName, UserSession userSession)

    {

        using (Entities ctx = CommonSERT.GetContext())

        {

            var result = (from ur in ctx.datUserRoles

                          where ur.AccountName.Equals(userName, StringComparison.CurrentCultureIgnoreCase)

                          select new

                          {

                              UserActive = ur.active,

                              UserROB = ur.ROB,

                              UserID = ur.ID

                          }).FirstOrDefault();

        }

        if (result != null) {

            userSession.UserActive = result.UserActive;

            userSession.UserROB  = result.UserROB;

            userSession.UserID = result.UserID;

        }

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!