tags:

views:

88

answers:

3

I have three tables I'm getting info from: User, Field, FieldUserInput. I already know the userId which is what I use to find out what fields the user has input. Then I want to get the value of those fields that the user has input in FieldUserInput.

I first wrote this query in plain old sql but I want to use LINQ as much as possible since that's why I use Entity Framework.

SELECT fielduserinput.field_idField, fielduserinput.userInput, fielduserinput.time
FROM fielduserinput
WHERE fielduserinput.userId = @userId

Any suggestions as to how I would write this in LINQ?

A: 
var response = fielduserinput
               .Where(x=>x.userid == @userid)
               .Select(x=>new { field_idfieldid = x.field_idfieldid, etc })
               .ToList()
wcpro
Could you explain what "fielduserinput.where" depicts? I get that it doesn't have that method.
Phil
Why `ToList`? No reason to fetch the entire result set if it's not needed.
Billy ONeal
@Phil: `x => x.userid == @userid` gets turned into a lambda function which returns the boolean result of x.userid == @userid. Note for that to work you'd have to replace @userid with a real variable name.
Billy ONeal
+2  A: 

Considering you have a datasource filled with data.

var matchingRows = from rows in fielduserinput.AsEnumarable()
                   where string.compare(rows["userId"].ToString(),userID)==0
                   select rows;
saurabh
Hehe -- that one looks like it actually compiles, unlike my own :P
Billy ONeal
Quick question: Why String.Compare instead of just using `==`?
Billy ONeal
Thanks! I like the style of it.
Phil
.AsEnumerable() uses the IEnumerable extension methods, and not the IQueryable extension methods. Then means the query is run using plain Linq2Objects and doesn't get optimized (translated into SQL). Of course this is no problem if your source is no IQueryable anyways.
CodeInChaos
A: 
var result = from row in fielduserinput
             where row.userId = "???"
             select new { row.field_idField, row.userInput, ...};
888