Question

I am trying to do something like a SQL 'in', which I understand to be more or less equivalent to 'contains' in LINQ.

This is the query I've come up with after reading through several other similar questions and this... http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

public ActionResult recentbookings(string recent_bookings)
{
    List<booking> bookings = db.bookings.Where(s => recent_bookings.Contains("36525")).ToList();
    return PartialView("_recentbookings", bookings);
}

This query returns every record in the table. I want and expect the query to return one record matching the id I'm passing in.

The 'recent_bookings' value is coming from localstorage through a javascript call...

var url = '@Url.Action("recentbookings", "booking")';
url += "?recent_bookings="+ localStorage['recent_bookings'];
$("#ajaxresult").load(url);

There happens to be only one item in local storage, which is '36525', which matches the hardcoded 'Contains("36525")' in my query.

I believe there's a simple problem with my query logic as I don't really understand it, compared with the SQL in.

Once I get this sorted out, I'll go on to parsing out multiple values from the incoming string.

Was it helpful?

Solution

public ActionResult recentbookings(string recent_bookings)
{
    var recent_bookings_array = new[] { int.Parse(recent_bookings) };
    booking[] bookings = db.bookings.Where(s => 
        recent_bookings_array.Contains(s.Id)).ToArray();
    return PartialView("_recentbookings", bookings);
}

You were using .Contains incorrectly. You are right, it is like an IN clause, but the object you invoke .Contains on should be like the IN (36525) part of your SQL query. The above query is basically saying "Give me all of the bookings where the booking ID is in this array of recent booking id's."

Why is your result returning all booking records?

...because the Where clause argument is a Func<T, bool>. Meaning, the result of the lambda expression must be either true or false. The expression in your question, s => recent_bookings.Contains("36525") will always return true, since the string "36525" is contained within your recent_bookings variable. Since it is always true, all of your rows get returned. You never checked anything against your data, only your local variables.

On another note, don't call .ToList on your result unless you need to add / remove items to / from it before returning the view. .ToArray is much faster, but returns an immutable collection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top