开发者

How to programmatically set label text - Linq To Entities

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 = Se开发者_开发知识库ssion["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.


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.


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();


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜