Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using Entity Framework in my ASP.NET, C#, Web Application. If I need to select a record from DataBase (in Data Access Layer), which method should I use? Linq query or a Lambda Expression?

Eg:-

//Linq        
var result = from a in db.myTable.Take(1) where a.Id == varId  select a;
return result.First();

//Lambda
return db.myTable.FirstOrDefault(a => a.Id == varId);

Is there any preferred way in this scenario or any advantage over the other?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
248 views
Welcome To Ask or Share your Answers For Others

1 Answer

Query Expression compiles into Method Expression (Lambda expression), so there shouldn't be any difference, In your code though you are accessing First and FirstOrDefault which would behave differently.

See: Query Syntax and Method Syntax in LINQ (C#)

and LINQ Query Expressions (C# Programming Guide)

At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...