EzDevInfo.com

linq-to-sql interview questions

Top linq-to-sql frequently asked interview questions

LINQ - Left Join, Group By, and Count

Let's say I have this SQL:

SELECT p.ParentId, COUNT(c.ChildId)
FROM ParentTable p
  LEFT OUTER JOIN ChildTable c ON p.ParentId = c.ChildParentId
GROUP BY p.ParentId

How can I translate this into LINQ to SQL? I got stuck at the COUNT(c.ChildId), the generated SQL always seems to output COUNT(*). Here's what I got so far:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.ParentId into grouped
select new { ParentId = grouped.Key, Count = grouped.Count() }

Thank you!


Source: (StackOverflow)

Difference Between Select and SelectMany

I've been searching the difference between Select and SelectMany but I haven't been able to find a suitable answer. I need to learn the difference when using LINQ To SQL but all I've found are standard array examples.

Can someone provide a LINQ To SQL example?


Source: (StackOverflow)

Advertisements

What is the syntax for an inner join in LINQ to SQL?

I'm writing a linq to sql statement & I'm just after the standard syntax for a normal inner join with an 'on' clause in C#.

ie how do you represent this in LINQ to SQL?:

select * from table1 
inner join table2 on table1.field = table2.field

EDIT: Real query to get all contacts for a dealer:

select DealerContact.*
from Dealer 
    inner join DealerContact on Dealer.DealerID = DealerContact.DealerID

Source: (StackOverflow)

Learning about LINQ

Overview

One of the things I've asked a lot about on this site is LINQ. The questions I've asked have been wide and varied and often don't have much context behind them. So in an attempt to consolidate the knowledge I've acquired on Linq I'm posting this question with a view to maintaining and updating it with additional information as I continue to learn about LINQ.

I also hope that it will prove to be a useful resource for other people wanting to learn about LINQ.

What is LINQ?

From MSDN:

The LINQ Project is a codename for a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

What this means is that LINQ provides a standard way to query a variety of datasources using a common syntax.

What flavours of LINQ are there?

Currently there are a few different LINQ providers provided by Microsoft:

There are quite a few others, many of which are listed here.

What are the benefits?

  • Standardized way to query multiple datasources
  • Compile time safety of queries
  • Optimized way to perform set based operations on in memory objects
  • Ability to debug queries

So what can I do with LINQ?

Chook provides a way to output CSV files
Jeff shows how to remove duplicates from an array
Bob gets a distinct ordered list from a datatable
Marxidad shows how to sort an array
Dana gets help implementing a Quick Sort Using Linq

Where to start?

A summary of links from GateKiller's question are below:
Scott Guthrie provides an intro to Linq on his blog
An overview of LINQ on MSDN

ChrisAnnODell suggests checking out:

What do I need to use LINQ?

Linq is currently available in VB.Net 9.0 and C# 3.0 so you'll need Visual Studio 2008 or greater to get the full benefits. (You could always write your code in notepad and compile using MSBuild)

There is also a tool called LinqBridge which will allow you to run Linq like queries in C# 2.0.

Tips and tricks using LINQ

This question has some tricky ways to use LINQ


Source: (StackOverflow)

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

How do I do this

Select top 10 Foo from MyTable

in Linq to SQL?


Source: (StackOverflow)

How to update Linq to SQL dbml file?

How to update Linq to SQL dbml file?


Source: (StackOverflow)

Entity Framework vs LINQ to SQL

Now that .NET v3.5 SP1 has been released (along with VS2008 SP1), we now have access to the .NET entity framework.

My question is this. When trying to decide between using the Entity Framework and LINQ to SQL as an ORM, what's the difference?

The way I understand it, the Entity Framework (when used with LINQ to Entities) is a 'big brother' to LINQ to SQL? If this is the case - what advantages does it have? What can it do that LINQ to SQL can't do on its own?


Source: (StackOverflow)

Linq to Sql: Multiple left outer joins

I'm having some trouble figuring out how to use more than one left outer join using LINQ to SQL. I understand how to use one left outer join. I'm using VB.NET. Below is my SQL syntax.

T-SQL

SELECT
    o.OrderNumber,
    v.VendorName,
    s.StatusName
FROM
    Orders o
LEFT OUTER JOIN Vendors v ON
    v.Id = o.VendorId
LEFT OUTER JOIN Status s ON
    s.Id = o.StatusId
WHERE
    o.OrderNumber >= 100000 AND
    o.OrderNumber <= 200000

Source: (StackOverflow)

Returning IEnumerable vs IQueryable

What is the difference between returning IQueryable<T> vs IEnumerable<T>?

IQueryable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;

IEnumerable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;

Will both be deferred execution and when should one be preferred over the other?


Source: (StackOverflow)

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures? [closed]

How would you rate each of them in terms of:

  1. Performance
  2. Speed of development
  3. Neat, intuitive, maintainable code
  4. Flexibility
  5. Overall

I like my SQL and so have always been a die-hard fan of ADO.NET and stored procedures but I recently had a play with Linq to SQL and was blown away by how quickly I was writing out my DataAccess layer and have decided to spend some time really understanding either Linq to SQL or EF... or neither?

I just want to check, that there isn't a great flaw in any of these technologies that would render my research time useless. E.g. performance is terrible, it's cool for simple apps but can only take you so far.

Update: Can you concentrate on EF VS L2S VS SPs rather than ORM VS SPs. I'm mainly interested by EF VS L2S. But am keen to have them compared against stored procs too since plain SQl is something I know a lot about.


Source: (StackOverflow)

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

Consider the IEnumerable extension methods SingleOrDefault() and FirstOrDefault()

MSDN documents that SingleOrDefault:

Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

whereas FirstOrDefault from MSDN (presumably when using an OrderBy() or OrderByDescending() or none at all),

Returns the first element of a sequence

Consider a handful of example queries, it's not always clear when to use these two methods:

var someCust = db.Customers
.SingleOrDefault(c=>c.ID == 5); //unlikely(?) to be more than one, but technically COULD BE

var bobbyCust = db.Customers
.FirstOrDefault(c=>c.FirstName == "Bobby"); //clearly could be one or many, so use First?

var latestCust = db.Customers
.OrderByDescending(x=> x.CreatedOn)
.FirstOrDefault();//Single or First, or does it matter?

Question

What conventions do you follow or suggest when deciding to use SingleOrDefault() and FirstOrDefault() in your LINQ queries?


Source: (StackOverflow)

LINQ-to-SQL vs stored procedures? [closed]

I took a look at the "Beginner's Guide to LINQ" post here on StackOverflow (http://stackoverflow.com/questions/8050/beginners-guide-to-linq), but had a follow-up question:

We're about to ramp up a new project where nearly all of our database op's will be fairly simple data retrievals (there's another segment of the project which already writes the data). Most of our other projects up to this point make use of stored procedures for such things. However, I'd like to leverage LINQ-to-SQL if it makes more sense.

So, the question is this: For simple data retrievals, which approach is better, LINQ-to-SQL or stored procs? Any specific pro's or con's?

Thanks.


Source: (StackOverflow)

Max or Default?

What is the best way to get the Max value from a LINQ query that may return no rows? If I just do

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).Max

I get an error when the query returns no rows. I could do

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter _
         Order By MyCounter Descending).FirstOrDefault

but that feels a little obtuse for such a simple request. Am I missing a better way to do it?

UPDATE: Here's the back story: I'm trying to retrieve the next eligibility counter from a child table (legacy system, don't get me started...). The first eligibility row for each patient is always 1, the second is 2, etc. (obviously this is not the primary key of the child table). So, I'm selecting the max existing counter value for a patient, and then adding 1 to it to create a new row. When there are no existing child values, I need the query to return 0 (so adding 1 will give me a counter value of 1). Note that I don't want to rely on the raw count of child rows, in case the legacy app introduces gaps in the counter values (possible). My bad for trying to make the question too generic.


Source: (StackOverflow)

efficient way to implement paging

Should I use LINQ's Skip() and Take() method for paging, or implement my own paging with a SQL query?

Which is most efficient? Why would I choose one over the other?

I'm using SQL Server 2008, ASP.NET MVC and LINQ.


Source: (StackOverflow)

Convert Linq Query Result to Dictionary

I want to add some rows to a database using Linq to SQL, but I want to make a "custom check" before adding the rows to know if I must add, replace or ignore the incomming rows. I'd like to keep the trafic between the client and the DB server as low as possible and minimize the number of queries.

To do this, I want to fetch as little information as required for the validation, and only once at the beginning of the process.

I was thinking of doing something like this, but obviously, it doesn't work. Anyone have an idea?

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj
        select (new KeyValuePair<int, DateTime>(ot.Key, ot.TimeStamp))
    )

What I'd like to have at the end would be a Dictionary, without having to download the whole ObjectType objects from TableObject.

I also considered the following code, but I was trying to find a proper way:

List<int> keys = (from ObjType ot in TableObj orderby ot.Key select ot.Key).ToList<int>();
List<DateTime> values = (from ObjType ot in TableObj orderby ot.Key select ot.Value).ToList<int>();
Dictionary<int, DateTime> existingItems = new Dictionary<int, DateTime>(keys.Count);
for (int i = 0; i < keys.Count; i++)
{
    existingItems.Add(keys[i], values[i]);
}

Source: (StackOverflow)