0

I use Asp.net 3.5 and EF 4.

I need find a specific row in my DataBase and display on a label a single value as string.

At the moment I use this code, it is working, so I find a single Object and read its properties.

 var myAuthor = (from at in context.CmsAuthors
             where at.AuthorId == myRow.AuthorId
             select at).Single();   
 myAuthorNameLabel.Text = myAuthor.LastName;

I would like to know:

  • If there is another syntax in Linq to achieve the same result.
  • How to do it using Lamba?
  • Which approach would you suggest me?

2 Answers 2

4

Here's the method syntax (using lambdas)

myAuthorNameLabel.Text = context.CmsAuthors
                           .Where(at => at.AuthorId == myRow.AuthorId)
                           .Select(at => at.LastName) 
                           .SingleOrDefault() ?? string.Empty;
Sign up to request clarification or add additional context in comments.

Comments

3

You can use:

 var myAuthorName = 
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Single().Select(a => a.LastName);

actually this would be even better:

var myAuthorName = 
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select(a => a.LastName).Single();

Update

An example of how to use with Anonymous type:

var myAuthorNames = 
    (from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select( a => new {a.LastName, a.FirstName}).Single();

6 Comments

Thanks, could you tell me why your second option would be even better?
Sure, the usage of Single executes the actual database query, so in the first case the query retrieves the entire Author object and then selects the last name out of it. The second method performs a minimal db query to retrieve only the last name column.
Ok I understand, what about using Anonymous Type? Could make even minimal db query? thanks for your help on this
In this case I don't think it can get any minimal that that. If you needed to retrieve two values then selecting an anonymous type would get you the minimal query.
Thanks Variant, may I ask you if you can write down here an example with Anonymous Type? Unfortunately I'm trying but with no success. Thanks once again!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.