Exception: Sequence contains more than one element in Asp.net Core

Dung Do Tien Oct 02 2021 133

Hello, I have a project with Asp.Net Core 3.1 and I created a function to get list of articles by brand and model as below:

public ArticleBrandModel GetArticleByBrandModel(int id)
{
    try
    {
        var result = QuerySP<ArticleBrandModel>("func_fe_getbrandmodelbyarticleid",
            new { _id = id });
        return result.SingleOrDefault() ?? new ArticleBrandModel();
    }
    catch (Exception ex)
    {
        Logger.Error(ex, ex.Message);
        return new ArticleBrandModel();
    }
}

But when I call this method I get an exception throw System.InvalidOperationException: Sequence contains more than one element. You can see detail exception below:

System.InvalidOperationException: Sequence contains more than one element 
at System.Linq.ThrowHelper.ThrowMoreThanOneElementException() 
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source) 
at APS.AP.Application.News.Stograge.Daoes.Impl.CarNewsDao.GetArticleBrandModel(Int32 id) 
in /src/Application/APS.AP.Application.News/Stograge/Daoes/Impl/CarNewsDao.cs:line 126"

I using PostgreSql database and PostgreHelper to help connect to database.

I tried debug and execute postgre function but it work well for me.

How can I resolve this issue?

Thanks for any suggestions.

Have 2 answer(s) found.
  • N

    Nkanyiso Sibanda Oct 02 2021

    You get exception sequence contains more than one element because you are using SingleOrDefault() method of LinQ and your list data is null. You need to check null before use it.

    You can change SingleOrDefault() to FirstOrDefault() method

    return result.FirstOrDefault() ?? new ArticleBrandModel();

    And it will solve for you.

  • T

    Thủy Lê Oct 02 2021

    I think you need to re-check your result variable. I think it is null and throw this exception. You can check null as bellow:

    return result?.SingleOrDefault() ?? new ArticleBrandModel();

    Or you can using if condition to check it.

    I hope it solve issue for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close