EzDevInfo.com

linq-to-entities interview questions

Top linq-to-entities frequently asked interview questions

What's the difference(s) between .ToList(), .AsEnumerable(), AsQueryable()?

I know some diefferences of L2E and L2O which the first implements IQueryable and the second implements IEnumerable and my Q scope is within EF 5.

My Q is what's the technical difference(s) of Those 3 methods. I see that in many situations all of them work. I also see using combinations of them like .ToList().AsQueryable().

1) What those method exactly mean?

2) Is there any performance or other issue about them in comparison to others?

3) Why using for example .ToList().AsQueryable() instead of .AsQueryable()?

Thanks in advance


Source: (StackOverflow)

linq to entities case sensitive comparison

This isn't a case-sensitive comparison in Linq to entities:

Thingies.First(t => t.Name == "ThingamaBob");

How can I achieve case sensitive comparison with Linq to entities?


Source: (StackOverflow)

Advertisements

"A lambda expression with a statement body cannot be converted to an expression tree"

In using the EntityFramework, I get the error "A lambda expression with a statement body cannot be converted to an expression tree" when trying to compile the following code:

Obj[] myArray = objects.Select(o =>
{
    var someLocalVar = o.someVar;

    return new Obj() { 
    Var1 = someLocalVar,
    Var2 = o.var2 };
}).ToArray();

I don't know what the error means and most of all how to fix it. Any help? Thanks


Source: (StackOverflow)

Linq to Entities join vs groupjoin

I have web searched but I still cant find a simple answer. Can someone please explain (in simple English) what a GroupJoin is? How is it different from a regular inner Join? Is it commonly used? Is it only for method syntax? What about query syntax? A c# code example would be nice.


Source: (StackOverflow)

Linq int to string

how do I cast and int into a string? None of the following do works:

from s in ctx.Services
    where s.Code.ToString().StartsWith("1")
    select s

from s in ctx.Services
    where Convert.ToString(s.Code).StartsWith("1")
    select s

from s in ctx.Services
    where ((string)s.Code).ToString().StartsWith("1")
    select s

EDIT

The error I get is:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression


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)

How to do SQL Like % in Linq?

I have a procedure in SQL that I am trying to turn into Linq:

SELECT O.Id, O.Name as Organization
FROM Organizations O
JOIN OrganizationsHierarchy OH ON O.Id=OH.OrganizationsId
where OH.Hierarchy like '%/12/%'

The line I am most concerned with is:

where OH.Hierarchy like '%/12/%'

I have a column that stores the hierarchy like /1/3/12/ for example so I just use %/12/% to search for it.

My question is, what is the Linq or .NET equivalent to using the percent sign?


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)

Linq to Entities - SQL "IN" clause

In T-SQL you could have a query like:

SELECT * FROM Users WHERE User_Rights IN ("Admin", "User", "Limited")

How would you replicate that in a LINQ to Entities query? Is it even possible?


Source: (StackOverflow)

Entity Framework 4 / POCO - Where to start? [closed]

I've been programming for a while and have used LINQ-To-SQL and LINQ-To-Entities before (although when using entities it has been on a Entity/Table 1-1 relationship - ie not much different than L2SQL)

I've been doing a lot of reading about Inversion of Control, Unit of Work, POCO and repository patterns and would like to use this methodology in my new applications.

Where I'm struggling is finding a clear, concise beginners guide for EF4 which doesn't assume knowledge of EF1.

The specific questions I need answered are:

Code first / model first? Pros/cons in regards to EF4 (ie what happens if I do code first, change the code at a later date and need to regenerate my DB model - Does the data get preserved and transformed or dropped?)

Assuming I'm going code-first (I'd like to see how EF4 converts that to a DB schema) how do I actually get started? Quite often I've seen articles with entity diagrams stating "So this is my entity model, now I'm going to ..." - Unfortunately, I'm unclear if they're created the model in the designer, saved it to generate code then stopped any further auto-code generation -or- They've coded (POCO)? classes and the somehow imported them into the deisgner view?

I suppose what I really need is an understanding of where the "magic" comes from and how to add it myself if I'm not just generating an EF model directly from a DB.

I'm aware the question is a little vague but I don't know what I don't know - So any input / correction / clarification appreciated.

Needless to say, I don't expect anyone to sit here and teach me EF - I'd just like some good tutorials/forums/blogs/etc. for complete entity newbies


Source: (StackOverflow)

Problem with converting int to string in Linq to entities

var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId, //Cannot implicitly convert type 'int' (ContactId) to 'string' (Value).
                Text = c.Name
            };
var items = from c in contacts
            select new ListItem
            {
                Value = c.ContactId.ToString(), //Throws exception: ToString is not supported in linq to entities.
                Text = c.Name
            };

Is there anyway I can achieve this? Note, that in VB.NET there is no problem use the first snippet it works just great, VB is flexible, im unable to get used to C#'s strictness!!!


Source: (StackOverflow)

How to use DbContext.Database.SqlQuery(sql, params) with stored procedure? EF Code First CTP5

I have a stored procedure that has three parameters and I've been trying to use the following to return the results:

context.Database.SqlQuery<myEntityType>("mySpName", param1, param2, param3);

At first I tried using SqlParameter objects as the params but this didn't work and threw a SqlException with the following message:

Procedure or function 'mySpName' expects parameter '@param1', which was not supplied.

So my question is how you can use this method with a stored procedure that expects parameters?

Thanks.


Source: (StackOverflow)

New transaction is not allowed because there are other threads running in the session LINQ To Entity

Any ideas on why this could be breaking?

foreach (var p in pp)
{
    ProjectFiles projectFile = (ProjectFiles)p;
    projectFile.Status = Constants.ProjectFiles_ERROR;
    projectFile.DateLastUpdated = DateTime.Now;
    context.SaveChanges();
}

I read that the workaround the issue, is to retrieve the results in one go before the foreach loop.

But didnt I do that? "pp" is the collection of results in my case


Source: (StackOverflow)

The cast to value type 'Int32' failed because the materialized value is null

I have the following code. I'm getting error:

"The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."

when CreditHistory table has no records.

var creditsSum = (from u in context.User
                  join ch in context.CreditHistory on u.ID equals ch.UserID                                        
                  where u.ID == userID
                  select ch.Amount).Sum();

How can I modify the query to accept null values?


Source: (StackOverflow)

Bulk-deleting in LINQ to Entities

Is there any way to bulk-delete a bunch of objects matching a given query in LINQ or LINQ-to-Entities? The only references that I can find are outdated, and it seems silly to iterate over and manually delete all objects I wish to remove.


Source: (StackOverflow)