Sequence contains no matching element ошибка

Well, I’d expect it’s this line that’s throwing the exception:

var documentRow = _dsACL.Documents.First(o => o.ID == id)

First() will throw an exception if it can’t find any matching elements. Given that you’re testing for null immediately afterwards, it sounds like you want FirstOrDefault(), which returns the default value for the element type (which is null for reference types) if no matching items are found:

var documentRow = _dsACL.Documents.FirstOrDefault(o => o.ID == id)

Other options to consider in some situations are Single() (when you believe there’s exactly one matching element) and SingleOrDefault() (when you believe there’s exactly one or zero matching elements). I suspect that FirstOrDefault is the best option in this particular case, but it’s worth knowing about the others anyway.

On the other hand, it looks like you might actually be better off with a join here in the first place. If you didn’t care that it would do all matches (rather than just the first) you could use:

var query = from target in _lstAcl.Documents
            join source in _dsAcl.Document
            where source.ID.ToString() equals target.ID
            select new { source, target };
foreach (var pair in query)
{
    target.Read = source.Read;
    target.ReadRule = source.ReadRule;
    // etc
}

That’s simpler and more efficient IMO.

Even if you do decide to keep the loop, I have a couple of suggestions:

  • Get rid of the outer if. You don’t need it, as if Count is zero the for loop body will never execute
  • Use exclusive upper bounds in for loops — they’re more idiomatic in C#:

    for (i = 0; i < _lstAcl.Documents.Count; i++)
    
  • Eliminate common subexpressions:

    var target = _lstAcl.Documents[i];
    // Now use target for the rest of the loop body
    
  • Where possible use foreach instead of for to start with:

    foreach (var target in _lstAcl.Documents)
    

Sequence contains no matching element is an error message from a C-Sharp application that occurs when a sequence (a collection of items, such as an array, list, or set) does not contain any element that matches a given criterion or condition.Sequence Contains No Matching Element Solved

This article will teach you why you’re seeing the sequence error and the steps that you can take to prevent it in your code and computing environment.

By using the solutions we’ll discuss in later sections of the article, you’ll save yourself tons of debugging time to write actual code. You’re about to dabble with some code, so get your code editor, and let’s get started.

Contents

  • Why There Are No Matching Elements in Your Sequence?
    • – The “First()” Method Did Not Find a Match for Your Condition
    • – You’re Working on an Empty Sequence
    • – The Condition to the “Where()” Method Is Out of Range
    • – Your Database Query Does Not Return Any Results
  • How To Fix the Sequence Error When There Is No Match?
    • – Replace “First()” With “Firstordefault()” in Your Code
    • – Perform a Check With “Any()” Before Using “First()”
    • – Ensure the Condition of “Where” Returns a Result
    • – Double-check Your Code and Database
  • Conclusion

Why There Are No Matching Elements in Your Sequence?

There are no matching elements in your sequence because of the following:

  • The “First()” method did not find a match for your condition
  • You’re working on an empty sequence
  • The condition to the “Where()” method is out of range
  • Your database query does not return any results

– The “First()” Method Did Not Find a Match for Your Condition

In your C-sharp code, if the search criteria to the “First()” method returns nothing, it will throw the “sequence contains no matching elements C#” error. Similarly, you’ll get the “sequence contains no matching element Power BI” error if the filter or sort criteria do not match any element.

For example, in the following C-sharp code, we have an array of odd integers, and we’re trying to find the first even number in the array using the “First()” method. Since there is no even number in the array, the “First()” method throws the exception.

using System;

using System.Linq;

class Program

{

static void Main()

{

int[] numbers = { 1, 3, 5, 7, 9 };

// Trying to find the first even number in the array

int firstEven = numbers.First(n => n % 2 == 0);

// Throws “System.InvalidOperationException: Sequence contains no matching element”

}

}

– You’re Working on an Empty Sequence

If you use LINQ to query an empty collection or database table, you can get the “sequence contains no matching element Entity Framework” exception message. For example, the following C-sharp code has an empty integer array number, and we’re trying to get the first element in the array.

However, if there are no elements to return, you’ll get the “sequence contains no matching element visual studio” exception message if you’re working in Visual Studio.

using System;

using System.Linq;

class Program

{

static void Main(string[] args)

{

int[] numbers = { };

int firstNumber = numbers.First();

Console.WriteLine(“The first number in the array is: ” + firstNumber);

}

}

– The Condition to the “Where()” Method Is Out of Range

The “Where()” method takes a condition that it uses to return data, and if this condition is out-of-range, it will throw the “InvalidOperationException”. The “Sequence contains no matching elements” will follow, and it’s mostly because it did not find any matching elements in your data.Cause of No Matching Elements in Your Sequence

For example, in the following code, the “Where()” method will throw an exception because it’s trying to look for a grade that is greater than the maximum grade in the list, and that is impossible.

using System;

using System.Collections.Generic;

using System.Linq;

class Program

{

static void Main(string[] args)

{

var students = new List<Student>

{

new Student { Name = “Alice”, Age = 18, Grade = 90 },

new Student { Name = “Bob”, Age = 17, Grade = 85 },

new Student { Name = “Charlie”, Age = 19, Grade = null },

new Student { Name = “David”, Age = 16, Grade = 92 }

};

var topStudentName = students.Where(s => s.Grade >

students.Max(s => s.Grade)).First().Name;

Console.WriteLine(topStudentName);

}

}

class Student

{

public string Name { get; set; }

public int Age { get; set; }

public int? Grade { get; set; }

}

– Your Database Query Does Not Return Any Results

When your database query does not return any results, you can get the “sequence contains no matching elements” exception message. This can happen due to the following:

  • Running a query that returns no results: This can happen if you are using a LINQ to SQL query to retrieve a single row, but the database table is empty, or the query criteria do not match any rows.
  • Querying a non-existent table: You have misspelt the table name in your query, or the table has been deleted from the database.

How To Fix the Sequence Error When There Is No Match?

To fix the sequence error when there are no matching elements, use any of the following:

  • Replace “First()” with “FirstOrDefault()” in your code
  • Perform a check with “Any()” before using “First()”
  • Ensure the condition of “Where” returns a result
  • Double-check your code and database

– Replace “First()” With “Firstordefault()” in Your Code

If the “First()” method in your code is causing the sequence exception, replace it with “FirstOrDefault”. For reference, the following code is the updated version of our first example and, now, we’re using the “FirstOrDefault()” method.

This method returns the default value of the data type (zero in this case) when the sequence is empty or does not contain any matching element. With this, we can check if the result is the default value (zero), and we can write an appropriate message to the console.

using System;

using System.Linq;

class Program

{

static void Main()

{

int[] numbers = { 1, 3, 5, 7, 9 };

// Trying to find the first even number in the array

int firstEvenOrDefault = numbers.FirstOrDefault(n => n % 2 == 0);

if (firstEvenOrDefault == 0)

{

Console.WriteLine(“No even numbers found.”);

}

else

{

Console.WriteLine($”First even number found: {firstEvenOrDefault}”);

}

}

}

– Perform a Check With “Any()” Before Using “First()”

If there is any chance that you’ll get an empty sequence in your code, check the sequence with “Any()”, and if it returns a result, you can safely use the “First()” method.Fix the Sequence Contains No Matching Element

However, as a guard against the error, you can set a default value for the first number, and you can return it if “Any()” returns empty. The following code shows you how it’s done, and you can apply a similar validation of arrays to solve the “sequence contains no matching element Web API” error.

using System;

using System.Linq;

class Program

{

static void Main(string[] args)

{

int[] numbers = { };

int firstNumber = 0;

if (numbers.Any())

{

firstNumber = numbers.First();

}

Console.WriteLine(“The first number in the array is: ” + firstNumber);

}

}

– Ensure the Condition of “Where” Returns a Result

When you’re working with the “Where()” method in your code, ensure the condition that you pass to it returns a result. Earlier, we showed you a code that did otherwise, and that resulted in the error. Specifically, the line that says “students.Where(s => s.Grade > students.Max(s => s.Grade)).First().Name”.

This is an impossible code because you can’t look for something that’s not there, and to correct this, we have to replace this code. The updated code will compare each student’s grade to the maximum grade in the list, and retrieve the name of the first student that meets this condition (in this case, it’s David).

using System;

using System.Collections.Generic;

using System.Linq;

class Program

{

static void Main(string[] args)

{

var students = new List<Student>

{

new Student { Name = “Alice”, Age = 18, Grade = 90 },

new Student { Name = “Bob”, Age = 17, Grade = 85 },

new Student { Name = “Charlie”, Age = 19, Grade = null },

new Student { Name = “David”, Age = 16, Grade = 92 }

};

var topStudentName = students.Where(s => s.Grade == students.Max(s => s.Grade)).First().Name;

Console.WriteLine(topStudentName);

}

}

class Student

{

public string Name { get; set; }

public int Age { get; set; }

public int? Grade { get; set; }

}

// Expected output: David

– Double-check Your Code and Database

If you’re seeing “sequence contains no matching elements” while working with databases, double-check your code and database.

As a guide, use the following list:

  • Ensure that your query is correctly written and that it is targeting the right table or column.
  • Check to see if the data you are querying exists in the database.
  • Use breakpoints, and debug your code to see what is happening before the error occurs.
  • Handle the exception by catching it and displaying an appropriate error message to your users.

Finally, you can use similar steps to solve the “sequence contains no matching element conga” exception message. In this context, review your configuration and code to ensure that your queries and data processing logic is correct.

Conclusion

This article explained why your sequence does not contain matching elements after a search and how to deal with it. Right now, you can proceed with your daily activities, but remember the following from the article:

  • Methods like “First()” and “Where()” will return the sequence exception if their condition returns nothing.
  • If you’re working on an empty sequence (like an empty array), you’ll also get the “sequence contains no matching elements” exception.
  • To solve the “sequence contains no matching elements” exception, replace the “First()” method with “FirstOrDefault.

With your newly found knowledge, you can prevent sequence errors in your code and applications. Take good care of yourself and have fun coding your next big application!

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  • Remove From My Forums
  • Question

  • User1548135827 posted

    I have been working on an MVC App for over 3 months now. I just added another controller with scaffolded views and now none of my views  are working.  This is happening in generated code, which has worked and been tested for 3 months.  It
    seems that anything that tries to read the DB now generated this same error;

    Server Error in ‘/’ Application.


    Sequence contains no matching element

    Description: An
    unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.InvalidOperationException: Sequence contains no matching element

    Source Error:

    Line 31:         public ActionResult Index()
    Line 32:         {
    Line 33:             return View( db.TagGroups.ToList());
    Line 34:         }
    Line 35: 


    Source File: c:UsersLouisDocumentsVisual Studio WorkInfoInfoControllersTagGroupsController.cs    Line: 33 

    Stack Trace:

    [InvalidOperationException: Sequence contains no matching element]
       System.Linq.Enumerable.Single(IEnumerable`1 source, Func`2 predicate) +2611349
       System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name) +146
       System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration) +650
       System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.<>c__DisplayClass1.<Configure>b__0(Tuple`2 pm) +125
       System.Data.Entity.Utilities.IEnumerableExtensions.Each(IEnumerable`1 ts, Action`1 action) +194
       System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration) +158
       System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride) +278
       System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride) +728
       System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest) +203
       System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest) +660
       System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest) +464
       System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) +570
       System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +103
       System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +143
       System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +171
       System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +594
       System.Data.Entity.Internal.InternalContext.Initialize() +31
       System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +39
       System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +137
       System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +38
       System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +107
       System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369
       System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
       pimpInfo.Controllers.TagGroupsController.Index() in c:UsersLouisDocumentsVisual Studio WorkpimpInfopimpInfoControllersTagGroupsController.cs:33
       lambda_method(Closure , ControllerBase , Object[] ) +101
       System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
       System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
       System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
       System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
       System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
       System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +73
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
       System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
       System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
       System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
       System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
       System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
       System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
       System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
       System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
       System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
       System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
       System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
       System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
       System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
       System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9751057
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Answers

  • User1548135827 posted

    Hi Krunal

    I was not using EF Database first Designer, I was using Code First and could not find a Model Browser.  I manually rebuilt the Code First from Database and it worked have way but by the time I got to the end I had the same problem.

    I made a copy and added a Database First emdx Model and did not save the connection.  I was then able to load it into the Model Browser.  I then rebuilt and it all worked, I then did it again with my original and it worked there too.

    Thank you for your assistance and the solution to this problem.

    There is a problem with this solution, all my model classes with their annotations were deleted in the process of fixing this issue.  Microsoft are getting rid of the Database design first approach. Which creates another problem how
    do you fix this when the Model browser is no longer available?  I now have to workout how to annotate the new Model classes that we generated and how do I migrate back to code first and should I knowing that it created this problem in the first place?

    Regards

    Lou

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

Hi

I have a LAB environment set up to test Data Quality Services.

This is the LAB Setup:

  • Server: With SQL Server 2012 DB locally installed.  DQS Server Installed.  DQS Client installed.
  • Workstation: DQS Client installed only, simulating Data Steward scenario

When CU1 released, I decided to upgrade my LAB to test the performance improvement in DQS.  I proceeded with the following steps:

  • Upgrade Server with CU1
  • Upgrade DQS Schema on Server
  • Upgrade DQS dlls on Server

From the server machine, all DQS functionality seemed to work fine.  On the Workstation machine, I started getting strange errors.  First it complained about parallel processing in a data quality cleansing project.  Maching the threads between
1 and 4 with a sql query made no difference.

I then thought the DQS client must be upgraded but couldn’t find a dqsinstaller.exe file on the workstation.  I then proceeded to run the CU1 setup package on the workstation.  On the Feature page it detected that DQS Client was the only installation
and proceeded with the upgrade without problem.

But the problems on the workstation with DQS client still persists.  If I try the exact same features on the Server, all works.  I can run the cleansing project, I can export matching policy results, no issues at all.

I can’t help but feel a sort of «upgrade» is necessary on the workstation that only has DQS client installed, but I can’t find any information.

Here is what happens:

I have set up a simple Knowledge Base (using a mix of DQS Data and the adventure works 2012 sample db) to check address information (Country, State, City, Address Line 1).

I have also set up a matching policy in the same KB

I use it to try and find «house hold» maches in the address data (i.e. two or more people live at the same address).

When I run a data quality project using the matching policy, on the data in the AdventureWorks 2012 sample database using the Person.address (and related tables) the project completes successfully.

However, when I try to export the result to a SQL table, I get the following error:

2012/05/30 05:04:26 PM|[]|1|INFO|PUID|Microsoft.Ssdqs.Proxy.EntryPoint.ProxyInit|Starting DQS ProxyInit: version [11.0.2316.0], machine name [WS1], user name [LABbaileym], operating system [Microsoft Windows NT 6.1.7601 Service Pack 1]…
2012/05/30 05:04:26 PM|[]|1|INFO|PUID|Microsoft.Ssdqs.Proxy.EntryPoint.ProxyInit|DQS ProxyInit started.
2012/05/30 05:04:50 PM|[]|1|ERROR|CLIENT|Microsoft.Ssdqs.Studio.ViewModels.Utilities.UIHelper|An error has occurred.
System.InvalidOperationException:Sequence contains no matching element;
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate);
   at Microsoft.Ssdqs.Studio.ViewModels.Data.DataSources.DatabaseHelper.GetStagingDatabase();
   at Microsoft.Ssdqs.Studio.ViewModels.ViewModels.Matching.MatchingExportViewModel.CreateTemporaryRepositoryMetadata(RepositoryMetadata source);
   at Microsoft.Ssdqs.Studio.ViewModels.ViewModels.Matching.MatchingExportViewModel.ExportMatchingContentCommandExecute(Object parameter);
   at Microsoft.Ssdqs.Studio.ViewModels.Utilities.UICommand.Execute(Object parameter);
   at Microsoft.Ssdqs.Studio.Views.Pages.Matching.MatchingExportView.MatchingExportExecute(Object sender, ExecutedRoutedEventArgs e);
   at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e);
   at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding);
   at System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute);
   at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute);
   at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e);
   at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e);
   at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target);
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target);
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs);
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised);
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args);
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted);
   at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated);
   at System.Windows.Input.RoutedCommand.ExecuteCore(Object parameter, IInputElement target, Boolean userInitiated);
   at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated);
   at System.Windows.Controls.Primitives.ButtonBase.OnClick();
   at System.Windows.Controls.Button.OnClick();
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e);
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e);
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget);
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target);
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs);
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised);
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent);
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e);
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget);
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target);
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs);
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised);
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args);
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args);
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted);
   at System.Windows.Input.InputManager.ProcessStagingArea();
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input);
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport);
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel);
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled);
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled);
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled);
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o);
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs);
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

I doubt that it has anything to do with security seeing as before the CU1 on the server, I could export results from this workstation to that database.

Any advice would be appreciated.

Thanks

Michelle

Я использую EF 6.1.0 и создаю службу WCF.

Сначала я создал библиотеку классов, содержащую мои сущности, Mappers и Context для инициализации EF.
Я также создал класс, содержащий экземпляр контекста и имеющий этот код:

public IQueryable<[Entity]> GetAll()
{
    return context.[Entity].AsQueryable();
}

С другой стороны, я создал службу WCF в одном проекте и вызывает функцию GetAll() в файле .svc следующим образом:

public List<[Entity]> GetList()
{
    [iObject] repository = new [Object](new Context());
    return repository.GetAll().ToList();
}

Проект строится. Я даже проверяю cconfiguration, и он находится в правой БД. Однако базы данных и таблиц, которые предположительно созданы, не существует, и появляется сообщение об ошибке «Последовательность не содержит соответствующий элемент».

Если это сбивает с толку, вы можете указать мне ссылку WCF-сервисов с использованием Code First Entity Framework.

Понравилась статья? Поделить с друзьями:
  • Sensor defect рено магнум ошибка
  • Sedo fss ru ошибка сервера код состояния 404
  • Securos ошибка подключения к серверу
  • Security spp ошибка что это
  • Security spp код ошибки 0x80041315