0

When you run Linq to Sql or Linq to Entites to get a list of records it runs query to select all fields from a table. Is it an efficient solution. Lets say: I run this LINQ

dim lstCustomers = from c in db.Customers select c

it run query to get all fields from a table whether i need all fields or not. I am using asp.net with MVC so should i write this query in view (where i only need CustomerID and name)

    dim lstCustomers = from c in db.Customers _
                       select new Customer with { c.CustomerID, c.Name }

If i have to use 2nd query then whats the advantage of LINQ and Entity Framework. This thing i can do with SQL query (with different syntax)

Anyone can help?

2 Answers 2

2

First of all, LINQ queries are evaluated lazily. That means that single line doesn't do anything but itself, so I assume you actually iterate the results with For Each.

The answer to your first question is yes, all fields are retrieved from the database with the first statement.

Yes, but in order to use SQL directly, you'll have to manually create entity classes, manually retrieve data using SqlDataReader or something to achieve the level of abstraction LINQ provides in that line. That's lots of more work on your behalf. With LINQ to SQL, you don't even need to explicitly write code to open a connection to database.

Sign up to request clarification or add additional context in comments.

Comments

0

actuly linq have different sets of advantages over writing normal writing sql queries:

if you wrote sql queries then overloaded steps:
1. you need a sql connection class
2. you need a sql command or sqldataadapter.
3.then you need a container like datatable and dataset.

so while using linq you dont need all those steps. just write the queries as you wrote above.

also incase you wrote something incorrect in your sqlquery then there is no compile time error. error only generates when you execute the query during runtime.
but unlike sql queries, linq provides you the compile time error.

also linq is best of strongly type collections.

Comments

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.