InvalidOperationException sequence contains more than one element even when only one element

Posted by user310256 on Stack Overflow See other posts from Stack Overflow or by user310256
Published on 2010-04-06T17:27:44Z Indexed on 2010/04/06 18:03 UTC
Read the original article Hit count: 254

I have three tables, tblCompany table, tblParts table and a link table between them tblLinkCompanyParts. Since tblLinkCompanyParts is a link table so the columns that it has are LinkCompanyPartID(primary key), CompanyID from tblCompany table and PartID from tblParts as foreign keys.

I have tied them up in the dbml file. In code if I write LinkCompanyParts.Parts (where LinkCompanyParts is an object of the tblLinkCompanyParts type) to get to the corresponding Part object I get the "InvalidOperationException: Sequence constains more than one element". I have looked at the data in the database and there is only one Parts record associated with the LinkCompanyPartID.

The stack trace reads like

at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Linq.EntityRef`1.get_Entity()
at ...

I read about SingleOrDefault vs FirstOrDefault but since the link table should have a one-one mapping therefore I think SingleOrDefault should work and besides "SingleOrDefault" statement is being generated behind the scenes in the designer.cs file at the following line

return this._Part.Entity;

Any ideas?

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about invalidoperationexception