Меню

Sequence contains more than one matching element ошибка

The point of the Single operator is to assert that a given sequence only has one item. For instance when retrieving a specific instance by primary key.

I suppose you want to mutate the state of any DressingItem matching the criteria, in which case you have some options, all involving enumerating the resultset, and executing some behavior.

There is no LINQ operator to specifically do this, since LINQ operators are meant to be pure. Pure functions are functions that do not have side effects, and this is exactly what you are trying to do.

There is, however, an extensionmethod on List<T> which does allow this. e.g.

this.DressingItems.Where(di => di.DressingInfo.CatID == catId
                            && di.ProductID == this.ProductID)
                  .ToList()
                  .ForEach(di => 
                  {
                      di.IsDefault = false
                  });

Or you could roll your own:

public static class EnumerableExtensions
{
    public static IEnumerable<T> ForEach<T>(
         this IEnumerable<T> source,
         Action<T> mutator)
    {
        var buffered = source.ToList();
        buffered.ForEach(mutator);
        return buffered;
    }
}

You might ask why the guys at Microsoft decided against adding this to the BCL: As I recall, the idea was that an extensionmethod vs. a foreach() { } construct would not yield much benefits in terms of typing anyway, and it wouldn’t help at all in terms of ambiguity. All other operators are side-effect free, and this one is explicitely designed to induce them.

  • Remove From My Forums
  • Question

  • User1860059286 posted

    Hello,

    I’m getting this error “Sequence contains more than one matching element”

     and I cant find out how to fix this  or  it happen ,

    I’m using code first and I’m getting it on every controller I’m tring to expose

    Any ideas ?

Answers

  • User197322208 posted

    1. return View(context.Schools.ToList());

    2. remove all properties that belong to other tables ( such as

    public int CityId { get; set; }
           
    public virtual  City Cities{ get; set; }

    and others.
    Assert no error
    Then add one by one.

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User197322208 posted

    recompile and breakpoint on the action that returns the view.

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

  • User750226543 posted

    OK, maybe something went wrong in the first solution? maybe just stick to the second.  Also, are you using re-sharper? worth looking at as it will help you out with missing references etc.

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

We keep getting an error that says «Sequence contains more than one matching element…»

We initially encountered the error while doing migrations (add-migration, update-database), but eventually learned that it also occurs on the first method call (i.e. Set) or property access (ChangeTracker) of the DbContext.

Deleting the migration files and generating a new one gets rid of the error, but we would like to move forward without removing the old migration files.

Stack trace:
System.InvalidOperationException: Sequence contains more than one matching element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source, Func2 predicate)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<>c__DisplayClass24f.b__246(<>f__AnonymousType2b2 <>h__TransparentIdentifier241) at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.IsModelOutOfDate(XDocument model, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains more than one matching element

RRS feed

  • Remove From My Forums
  • Вопрос

Ответы

  • As of this morning the error «Sequence contains more than one matching element» is
    no longer occurring for me.

    • Помечено в качестве ответа
      Fanny Liu
      16 июня 2014 г. 6:15

Все ответы

  • I’m also having a very similar problem with a slightly different error. If I don’t specify a database when logging in, I see this error:

    ‘[MoreThanOneMatch]
    Arguments: 
    Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=5.1.30214.00&File=System.Core.dll&Key=MoreThanOneMatch’

    Visiting the suggested link is useless.

    If I specify a database to connect to, then I can login, but see the same error again, similar to you. As yet I’ve found no cause for this and it’s the first time seeing it in 2 years. It seems to be a problem on all my Sql Azure instances.

    A friend working in the same building is able to login just fine with no issues.

  • Same exact issue here.   Started a couple of days ago.  Doesn’t solve the problem, but I can use SQL managment studio and connect to all databases at the same time.

  • Hello,

    Based on your descritpion, you create a SQL database with WEB edition and try to connect to the MASTER database from Windows Azure Management portal. But it is failed with «Sequence contains more than one matching element» occasionally.
    Due to the uncertainty and randomness factors, it requires higher level troubleshooting methods.I suggest you contact Windows Azure support team by creating a support ticket at 
    http://www.windowsazure.com/en-us/support/contact if you recevied this error again.

    As for drop login, it may caused by the premssion. In SQL databae, only server-level principal login (created by the provisioning process) or the credentials of an existing member of the «loginmanager» database role can manage logins. If you are not use
    a server-level principal login, please ask the adminstrator add the login to loginmanager databaserole:
    EXEC sp_addrolemember ‘loginmanager’, ‘login-you-used’;

    Reference:http://msdn.microsoft.com/en-us/library/azure/ee336235.aspx

    Regards,
    Fanny Liu

    If you have any feedback on our support, please click here. 


    Fanny Liu

    TechNet Community Support

  • Hi Fanny

    [quote]» … But it is failed with «Sequence contains more than one matching element»
    occasionally.

    Due to the uncertainty and randomness factors …
    if you recevied [sic] this error again. «[/quote]

    The above statement is incorrect. There’s nothing «occasional» about the issue. It happens every time.

    I’ll hold off on escalating because this is not due to «uncertainty and randomness factors» that you mention.

    Please investigate further based on my feedback.

    Thanks, Mark.


    Mark

    • Изменено
      ITPSB
      5 июня 2014 г. 6:36
      typo2

  • Hi Fanny

    I am the Administrator and am logged in as such. There is only one set of credentials and that’s what I use. I’m not sure what you mean by»

    «EXEC sp_addrolemember ‘loginmanager’, ‘login-you-used'»

    This is a LightSwitch app and people — like me — who have been encouraged to develop and deploy our own LOB apps do not have access to techo’s who understand what you are saying. We need a straight-forward answer
    to what should be a straight-forward issue.

    [quote] As for drop login, it may caused by the premssion. In SQL databae, only server-level principal login (created by the provisioning process) or the credentials of an existing member of the «loginmanager» database role can manage logins. If
    you are not use a server-level principal login, please ask the adminstrator add the login to loginmanager databaserole:
    EXEC sp_addrolemember ‘loginmanager’, ‘login-you-used’;[/quote]


    Mark

    • Изменено
      ITPSB
      5 июня 2014 г. 6:37
      typo

  • I have a similar problem.

    Trying to Manage the SQL Server (optional database name left blank) I get the following «Sequence contains more than one matching element» error —

    If I do supply a database name, I can login — but then I see the same error at the top of the dialog — under the «Failed to Create Context» error.

    Failed to create context

    This was not happening before — only started happening a few days ago, but the behaviour is consistent — I was hoping it would go away by itself — no such luck so far.

  • I am getting the same behavior on all of my tested SQL Servers. This was not happening a few days
    ago for us as well.

    • Изменено
      jehandwerker
      9 июня 2014 г. 18:37

  • I am seeing this same issue. First, it started happening with an Azure SQL Server I had created a few weeks ago (server located in North Central US location). I can connect to the server using SQL Management Studio, but I cannot use the web-based management
    system. I just created a brand-new Azure SQL Server, on a completely different Azure subscription, in the North Central US location, and I am getting the exact same issue when trying to connect through the web-based management system.

    This seems to be a relatively recent issue, so I’m hoping it gets fixed quickly.

  • As of this morning the error «Sequence contains more than one matching element» is
    no longer occurring for me.

    • Помечено в качестве ответа
      Fanny Liu
      16 июня 2014 г. 6:15

  • Yeah everything is looking good for me too.

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.

Последовательность содержит более одного элемента


У меня возникли проблемы с получением списка типа «RhsTruck» через Linq и его отображением.

RhsTruck имеет только свойства Make, Model, Serial и т. Д. RhsCustomer имеет свойства CustomerName, CustomerAddress и т. Д.

Я все время получаю ошибку «Последовательность содержит более одного элемента». Любые идеи? Я неправильно подхожу к этому?

public RhsCustomer GetCustomer(string customerNumber)
{
    using (RhsEbsDataContext context = new RhsEbsDataContext() )
    {
        RhsCustomer rc = (from x in context.custmasts
                          where x.kcustnum == customerNumber
                          select new RhsCustomer()
                        {
                            CustomerName = x.custname,
                            CustomerAddress = x.custadd + ", " + x.custcity
                            CustomerPhone = x.custphone,
                            CustomerFax = x.custfax
                        }).SingleOrDefault();
        return rc;
    }
}

public List<RhsTruck> GetEquipmentOwned(RhsCustomer cust)
{
    using (RhsEbsDataContext context = new RhsEbsDataContext())
    {
        var trucks = (from m in context.mkpops
                      join c in context.custmasts
                        on m.kcustnum equals c.kcustnum
                      where m.kcustnum == cust.CustomerNumber
                      select new RhsTruck
                    {
                        Make = m.kmfg,
                        Model = m.kmodel,
                        Serial = m.kserialnum,
                        EquipID = m.kserialno1,
                        IsRental = false
                    }).ToList();
        return trucks;
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    string testCustNum = Page.Request.QueryString["custnum"].ToString();

    RhsCustomerRepository rcrep = new RhsCustomerRepository();
    RhsCustomer rc = rcrep.GetCustomer(testCustNum);
    List<RhsTruck> trucks = rcrep.GetEquipmentOwned(rc);

    // I want to display the List into a Gridview w/auto-generated columns
    GridViewTrucks.DataSource = trucks;
    GridViewTrucks.DataBind();   
}


Ответы:


Проблема в том, что вы используете SingleOrDefault. Этот метод будет успешным только тогда, когда коллекции содержат ровно 0 или 1 элемент. Я считаю, что вы ищете то, FirstOrDefaultчто будет успешным, независимо от того, сколько элементов в коллекции.







SingleOrDefaultгенерирует, Exceptionесли в последовательности более одного элемента.

Очевидно, ваш запрос в GetCustomerобнаруживает более одного совпадения. Таким образом, вам нужно будет либо уточнить свой запрос, либо, скорее всего, проверить свои данные, чтобы понять, почему вы получаете несколько результатов для данного номера клиента.


Use FirstOrDefault insted of SingleOrDefault..

SingleOrDefault возвращает SINGLE элемент или null, если элемент не найден. Если в вашем Enumerable обнаружены 2 элемента, он выдает исключение, которое вы видите

FirstOrDefault возвращает ПЕРВЫЙ найденный элемент или null, если элемент не найден. поэтому, если есть 2 элемента, которые соответствуют вашему предикату, второй игнорируется

   public int GetPackage(int id,int emp)
           {
             int getpackages=Convert.ToInt32(EmployerSubscriptionPackage.GetAllData().Where(x
   => x.SubscriptionPackageID ==`enter code here` id && x.EmployerID==emp ).FirstOrDefault().ID);
               return getpackages;
           }

 1. var EmployerId = Convert.ToInt32(Session["EmployerId"]);
               var getpackage = GetPackage(employerSubscription.ID, EmployerId);


К вашему сведению, вы также можете получить эту ошибку, если EF Migrations пытается запустить без настроенной базы данных, например, в тестовом проекте.

Преследовал это в течение нескольких часов, прежде чем я понял, что это была ошибка в запросе, но не из-за запроса, а потому, что это произошло, когда Migrations запустил, чтобы попытаться создать Db.


Как указывает @Mehmet, если ваш результат возвращает более одного сообщения, вам необходимо изучить ваши данные, поскольку я подозреваю, что у вас есть клиенты, разделяющие номер клиента, не по дизайну.

Но я хотел дать вам краткий обзор.

//success on 0 or 1 in the list, returns dafault() of whats in the list if 0
list.SingleOrDefault();
//success on 1 and only 1 in the list
list.Single();

//success on 0-n, returns first element in the list or default() if 0 
list.FirstOrDefault();
//success 1-n, returns the first element in the list
list.First();

//success on 0-n, returns first element in the list or default() if 0 
list.LastOrDefault();
//success 1-n, returns the last element in the list
list.Last();

для получения дополнительных выражений Linq посмотрите System.Linq.Expressions

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Secret net ошибка подключения к ядру
  • Seo ошибки что это