LINQ Sequence contains more than one element

Recently I ran into an issue with the contains method in LINQ in conjunction with the SingleOrDefault method.

My query was similar to:

var data = (from i in ctx.DataContext.orders
where order.Contains(i.Name)
select i).SingleOrDefault();

and this was throwing the error:

System.InvalidOperationException: Sequence contains more than one element

Turns out the Contains translated to a LIKE '%...%' and was returning multiple records.  By changing this to i.Name == order, then I got back the single result I was expecting.

Add comment