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 offor
to start with:foreach (var target in _lstAcl.Documents)
- 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: 33Stack 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
-
Marked as answer by
Я использую 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.
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
Comments
Rokvach
added
Bug
Something isn’t working
Code
Programming task
Severe
An issue that causes severe problems and occurs consistently/frequently
Networking
Issue related to multiplayer or networking
labels
Apr 24, 2022
Regalis11
removed
the
Need more info
Insufficient information to resolve the issue (e.g. steps to reproduce a bug)
label
Jun 3, 2022
Rokvach
added
the
Unstable
Tickets that are included and being tested in the current Unstable build.
label
Jun 8, 2022
Rokvach
removed
the
Unstable
Tickets that are included and being tested in the current Unstable build.
label
Jun 11, 2022
Regalis11
added
the
Unstable
Tickets that are included and being tested in the current Unstable build.
label
Jun 29, 2022
Regalis11
removed
the
Unstable
Tickets that are included and being tested in the current Unstable build.
label
Jul 21, 2022
Regalis11
added
the
Unstable
Tickets that are included and being tested in the current Unstable build.
label
Aug 20, 2022
Rokvach
removed
the
Unstable
Tickets that are included and being tested in the current Unstable build.
label
Sep 28, 2022