masoud
masoud

Reputation: 925

error "Sequence contains no elements"

i have used below linq query code but it returns "Sequence contains no elements" , i am sure there is one item that should be return.

the code is like below:

tblDocTranstoCon doctranstocon =_DataContext.tblDocTranstoCons
                       .Single(dtcon => (dtcon.Docid == _DocID)
                                     && (dtcon.Transid==e.TransmittoconID)
                                     && (dtcon.Transid==e.TransID));

Upvotes: 1

Views: 372

Answers (2)

CloudyMarble
CloudyMarble

Reputation: 37566

To solve the problem replace the method Single() call with SingleOrDefault() method. The method SingleOrDefault() returns a null value if there are no source records that matches to the filtering criteria. see here

Upvotes: 0

cuongle
cuongle

Reputation: 75296

You should use SingleOrDefault if there is no item returned.

tblDocTranstoCon doctranstocon =_DataContext.tblDocTranstoCons
   .SingleOrDefault(dtcon => (dtcon.Docid == _DocID)
                   && (dtcon.Transid == e.TransmittoconID)
                   && (dtcon.Transid == e.TransID));

Upvotes: 2

Related Questions