argyle
argyle

Reputation: 1339

LINQ to SQL bug? Sequence contains more than one element

I'm using the following query:

            return (
                from c in dataContext.Contacts
                where c.ContactID == contactID
                select c
            ).SingleOrDefault();

In this case, by stepping through, "contactID" equals "6646". "c.ContactID" is the primary key field on the "Contact" table in SQL Server 2008 database. I have run a simple select query in SSMS

select * from contact where contactid = 6646

I get one result. But the LINQ to SQL query throws the "Sequence contains more than one element" error.

I have double and triple checked connection strings and primary key columns definitions. It's not clear to me how this can be happening.

Upvotes: 1

Views: 644

Answers (3)

argyle
argyle

Reputation: 1339

Ultimately came down to using LoadOptions to load related objects, one of which was defined in LINQ to SQL to be 1-1. However, in the associated table there were two records associated. So although the primary table the query was running against contained only one element, as expected, LINQ to SQL was using a Left Join to load the related objects, one of which was duplicated, causing two records to be returned.

Upvotes: 1

Leandro Soares
Leandro Soares

Reputation: 2972

Use FirstOrDefault.

SingleOrDefault is used when you are expecting only one item, i know that in this case it wouldn't be a problem but give it a try.

Upvotes: 0

BSG
BSG

Reputation: 1

That is an InvalidOperationException thrown by the Single method.

This method is supposed to return only one element, and your query is returning more than one, you have to check the criteria you use on your query.

It will also throw an exception if it doesn't find an element. You can use SingleOrDefault() method to return null (or default value, i.e. 0 for int) if there are no records.

If you are expecting multiple elements but just one the first one, you can use First instead of Single or FirstOrDefault.

try to debug and put a Where instead the Single so you will be able to see what are the rows that shouldn't be there

Upvotes: 1

Related Questions