views:

51

answers:

3

Hello all.

I have to set the label text of a load of differnet labels on a web page based upon user preferences.

I have the following code that is place upon the label load event (probably wrong!)

string memberid = Session["MemberID"].ToString();
            string locationid = Session["LocationID"].ToString();
            string userName = Membership.GetUser().UserName;
            string uuf1 = "UnitUserField1";

            MyEntities lblUUF1Text = new MyEntities();

            lblUUF1.Text = lblUUF1Text.tblUserPreferences
                            .Where(p => p.MemberID == memberid && p.LocationID == locationid && p.Username == userName && p.ColumnName == uuf1)
                            .Select(p => p.Alias)
                            .ToString();

However when I run this, the label text returned is:

System.Data.Objects.ObjectQuery`1[System.String]

Can someone point me in the error of my ways. I'm feeling very, very thick at the moment.

+2  A: 

You need a .First() in there

lblUUF1.Text = lblUUF1Text.tblUserPreferences
                            .Where(p => p.MemberID == memberid && p.LocationID == locationid && p.Username == userName && p.ColumnName == uuf1)
                            .Select(p => p.Alias).First().ToString();
BioBuckyBall
Thanks Lucas - really appreciate the help given to a simpleton.
Ricardo Deano
+1  A: 

You're writing a query and then asking that query to be converted to a string. Do you only want the first result of that query? If so, it's easy:

lblUUF1.Text = lblUUF1Text.tblUserPreferences
                          .Where(p => p.MemberID == memberid && 
                                 p.LocationID == locationid && 
                                 p.Username == userName && p.ColumnName == uuf1)
                        .Select(p => p.Alias)
                        .First();

(I'm assuming that the type of p.Alias is already string, but that you included the call to ToString as an attempt to coerce the query into a string to make it compile.)

Note that if there are no results, that will blow up with an exception. Otherwise it'll take the first result. Other options are:

  • Sure there's exactly one result? Use Single()
  • Think there's either zero or one? Use SingleOrDefault(), store in a local variable and set the label text if the result isn't null.
  • Think there's anything from zero to many? Use FirstOrDefault() in the same way.
Jon Skeet
Cheers Jon, you're a legend and always seem to bail me out! I also really appreciate the extra info you put on your answers, it really helps me in learning this.
Ricardo Deano
A: 

ToString() will return the object type as you see, what you will need to do is this:

lblUUF1.Text = lblUUF1Text.tblUserPreferences
                .Where(p => p.MemberID == memberid && p.LocationID == locationid && p.Username == userName && p.ColumnName == uuf1)
                .Select(p => p.Alias).SingleOrDefault();
Scott Lance