Error number 207 state 1 class 16

I am using Asp .netcore 2.0 on Visual Studio 15.7.4 and Its in app Identity system. According to this post in order to add new profile data all I need to do is to add it inside ApplicationUsers.cs ...

I am using Asp .netcore 2.0 on Visual Studio 15.7.4 and Its in app Identity system.
According to this post in order to add new profile data all I need to do is to add it inside ApplicationUsers.cs and the add migration and update database. Migration works fine before adding the new property but fails after it with the error below.
Adding Property:

namespace WebApplication6.Models
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        public Int64 Contact { get; set; }
    }

}

There is a Invalid column name 'Contact' inside the error, do I have to add it anywhere else?
The Error:

PM> add-migration "Contact"
Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:UsersURAppDataLocalASP.NETDataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.0.3-rtm-10026 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (175ms) [Parameters=[@__normalizedName_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
      SELECT TOP(1) [r].[Id], [r].[ConcurrencyStamp], [r].[Name], [r].[NormalizedName]
      FROM [AspNetRoles] AS [r]
      WHERE [r].[NormalizedName] = @__normalizedName_0
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (202ms) [Parameters=[@__normalizedEmail_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
      SELECT TOP(1) [u].[Id], [u].[AccessFailedCount], [u].[ConcurrencyStamp], [u].[Contact], [u].[Email], [u].[EmailConfirmed], [u].[LockoutEnabled], [u].[LockoutEnd], [u].[NormalizedEmail], [u].[NormalizedUserName], [u].[PasswordHash], [u].[PhoneNumber], [u].[PhoneNumberConfirmed], [u].[SecurityStamp], [u].[TwoFactorEnabled], [u].[UserName]
      FROM [AspNetUsers] AS [u]
      WHERE [u].[NormalizedEmail] = @__normalizedEmail_0
System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'Contact'.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__108_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()
ClientConnectionId:483a79cf-66d7-429e-86ff-1685217e9265
Error Number:207,State:1,Class:16
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred in the database while iterating the results of a query for context type 'WebApplication6.Data.ApplicationDbContext'.
      System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'Contact'.
         at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__108_0(Task`1 result)
         at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
         at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
         at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
         at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<BufferlessMoveNext>d__10.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<MoveNext>d__9.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
         at System.Linq.AsyncEnumerable.<FirstOrDefault_>d__165`1.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.<MoveNext>d__3.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
         at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.<MoveNextCore>d__7.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
         at System.Linq.AsyncEnumerable.AsyncIterator`1.<MoveNext>d__10.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
      ClientConnectionId:483a79cf-66d7-429e-86ff-1685217e9265
      Error Number:207,State:1,Class:16
System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'Contact'.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__108_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<BufferlessMoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<MoveNext>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.<FirstOrDefault_>d__165`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.<MoveNext>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.<MoveNextCore>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.AsyncIterator`1.<MoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
ClientConnectionId:483a79cf-66d7-429e-86ff-1685217e9265
Error Number:207,State:1,Class:16
Application startup exception: System.AggregateException: One or more errors occurred. (Invalid column name 'Contact'.) ---> System.Data.SqlClient.SqlException: Invalid column name 'Contact'.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__108_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<BufferlessMoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<MoveNext>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.<FirstOrDefault_>d__165`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.<MoveNext>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.<MoveNextCore>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.AsyncIterator`1.<MoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<ExecuteSingletonAsyncQuery>d__23`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at WebApplication6.Startup.<CreateUserRoles>d__1.MoveNext() in C:UsersURsourcereposWebApplication6WebApplication6Startup.cs:line 38
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at WebApplication6.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services) in C:UsersURsourcereposWebApplication6WebApplication6Startup.cs:line 114
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
---> (Inner Exception #0) System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'Contact'.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__108_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<BufferlessMoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.<MoveNext>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.<FirstOrDefault_>d__165`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable`1.Enumerator.<MoveNext>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator`2.<MoveNextCore>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.AsyncIterator`1.<MoveNext>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<ExecuteSingletonAsyncQuery>d__23`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at WebApplication6.Startup.<CreateUserRoles>d__1.MoveNext() in C:UsersURsourcereposWebApplication6WebApplication6Startup.cs:line 38
ClientConnectionId:483a79cf-66d7-429e-86ff-1685217e9265
Error Number:207,State:1,Class:16<---

My .csproj file just in case:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <UserSecretsId>aspnet-WebApplication6-32ACCB41-2BB0-426F-BD8D-B363DADD5CB0</UserSecretsId>
  </PropertyGroup>


  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.3" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.4" PrivateAssets="All" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
    <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.2" />
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
  </ItemGroup>

</Project>

Hello,

I’m getting the following errors when SQL-NS instance fires my rule:

Description: The running of the rule failed. Please check the rule.
EventParameters:
  Application Name: Messages
  Quantum ID: 30040
  Rule Firing ID: 21218
  Rule Name: MessageEventRule
  Notification Throttle: 1000
  Event Class ID: 1
  Subscription Class ID: 1
  Rule ID: 2
  Rule Action: EXEC stp_Insert_Message_Alerts
  Stored Procedure Name: [dbo].[NSFire2]

SqlServerError:
  Error Number: 0
  Source: .Net SqlClient Data Provider
  Number: 207
  State: 1
  Class: 16
  Server: NOCMON-DEV
  Message: Invalid column name 'Date'.
  Procedure: 
  Line Number: 16

  Error Number: 1
  Source: .Net SqlClient Data Provider
  Number: 207
  State: 1
  Class: 16
  Server: NOCMON-DEV
  Message: Invalid column name 'Date'.
  Procedure: 
  Line Number: 16

Description: Invalid column name 'Date'.
Invalid column name 'Date'.
InstanceName: NOCMon
ApplicationName: Messages
Component: Generator
Thread: 4


For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

My ADF looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns="http://www.microsoft.com/MicrosoftNotificationServices/ApplicationDefinitionFileSchema">

  <!-- Version -->

  <!-- Database Definition -->

  <!-- Event Classes -->
  <EventClasses>
    <EventClass>
      <EventClassName>NOCMonMessageEvents</EventClassName>
      <Schema>
        <Field>
          <FieldName>SourceID</FieldName>
          <FieldType>int</FieldType>
        </Field>
		<Field>
		  <FieldName>ErrorCategoryID</FieldName>
		  <FieldType>int</FieldType>
		</Field>
        <Field>
          <FieldName>Date</FieldName>
          <FieldType>datetime</FieldType>
        </Field>
        <Field>
          <FieldName>Station</FieldName>
          <FieldType>nvarchar(50)</FieldType>
        </Field>
        <Field>
          <FieldName>Message</FieldName>
          <FieldType>nvarchar(max)</FieldType>
        </Field>
        <Field>
          <FieldName>StatusID</FieldName>
          <FieldType>int</FieldType>
        </Field>
		<Field>
		  <FieldName>nUser</FieldName>
		  <FieldType>nvarchar(50)</FieldType>
		</Field>
		<Field>
		  <FieldName>nSubject</FieldName>
		  <FieldType>nvarchar(max)</FieldType>
		</Field>
      </Schema>
      <IndexSqlSchema>
        <SqlStatement>
			CREATE INDEX myIndex
			ON NOCMonMessageEvents ( SourceID );
		</SqlStatement>
      </IndexSqlSchema>
		<Chronicles>
			<Chronicle>
				<ChronicleName>NOCMonMessageEventsChronicle</ChronicleName>
				<SqlSchema>
					<SqlStatement>
						IF EXISTS(SELECT name FROM dbo.sysobjects WHERE name = 'NOCMonMessageEventsChronicle')
						DROP TABLE dbo.NOCMonMessageEventsChronicle
						CREATE TABLE NOCMonMessageEventsChronicle
						( [SourceID] int,
						[ErrorCategoryID] int,
						[Date] DateTime,
						[Station] nvarchar(50),
						[Message] nvarchar(max),
						[StatusID] int,
						[nUser] nvarchar(50),
						[nSubject] nvarchar(max))
					</SqlStatement>
				</SqlSchema>
			</Chronicle>
		</Chronicles>
		<ChronicleRule>
			<RuleName>NOCMonMessageEventsChronicleRule</RuleName>
			<Action>
				INSERT INTO NOCMonMessageEventsChronicle (SourceID, ErrorCategoryID, Date, Station, Message, StatusID, [nUser], nSubject)
				SELECT	E.SourceID, E.ErrorCategoryID, E.Date, E.Station, E.Message, E.StatusID, E.[nUser], E.nSubject
				FROM	NOCMonMessageEvents E
			</Action>
			<ActionTimeout>PT10M</ActionTimeout>
		</ChronicleRule>
    </EventClass>
  </EventClasses>

  <!-- Subscription Classes -->
  <SubscriptionClasses>
    <SubscriptionClass>
      <SubscriptionClassName>NOCMonMessageEventSubscription</SubscriptionClassName>
      <Schema>
        <Field>
          <FieldName>DeviceName</FieldName>
          <FieldType>nvarchar(255)</FieldType>
        </Field>
        <Field>
          <FieldName>SubscriberLocale</FieldName>
          <FieldType>nvarchar(10)</FieldType>
        </Field>
		  <Field>
			  <FieldName>SourceID</FieldName>
			  <FieldType>int</FieldType>
		  </Field>
		  <Field>
			  <FieldName>ErrorCategoryID</FieldName>
			  <FieldType>int</FieldType>
		  </Field>
		  <Field>
			  <FieldName>Station</FieldName>
			  <FieldType>nvarchar(50)</FieldType>
		  </Field>
		<Field>
		  <FieldName>Description</FieldName>
		  <FieldType>nvarchar(max)</FieldType>
		</Field>
		  <Field>
			  <FieldName>Threshold</FieldName>
			  <FieldType>int</FieldType>
		  </Field>
		  <Field>
			  <FieldName>TimeOfDayRangeBegin</FieldName>
			  <FieldType>nvarchar(50)</FieldType>
		  </Field>
		  <Field>
			  <FieldName>TimeOfDayRangeEnd</FieldName>
			  <FieldType>nvarchar(50)</FieldType>
		  </Field>
		  <Field>
			  <FieldName>TimeBuffer</FieldName>
			  <FieldType>nvarchar(50)</FieldType>
		  </Field>
		  <Field>
			  <FieldName>AlarmGrouping</FieldName>
			  <FieldType>bit</FieldType>
		  </Field>
		  <Field>
			  <FieldName>GroupingTime</FieldName>
			  <FieldType>nvarchar(50)</FieldType>
		  </Field>
		  <Field>
			  <FieldName>ElementContainer</FieldName>
			  <FieldType>nvarchar(MAX)</FieldType>
		  </Field>
		  <Field>
			  <FieldName>AcknowledgeNotification</FieldName>
			  <FieldType>bit</FieldType>
		  </Field>
		  <Field>
			  <FieldName>SecondaryNotification</FieldName>
			  <FieldType>nvarchar(MAX)</FieldType>
		  </Field>
		  <Field>
			  <FieldName>TertiaryNotification</FieldName>
			  <FieldType>nvarchar(MAX)</FieldType>
		  </Field>
      </Schema>
      <EventRules>
        <EventRule>
          <RuleName>MessageEventRule</RuleName>
          <EventClassName>NOCMonMessageEvents</EventClassName>
			<ConditionAction>
			  <SqlLogin>NSRulesEvaluator</SqlLogin>
			  <SqlUser>NSRulesEvaluator</SqlUser>
			  <InputName>NOCMonMessageEvents</InputName>
				<SqlExpression>
					EXEC stp_Insert_Message_Alerts
				</SqlExpression>
			</ConditionAction>
        </EventRule>
      </EventRules>
    </SubscriptionClass>
	  <SubscriptionClass>
		  <SubscriptionClassName>ScheduledSubscriptions</SubscriptionClassName>
		  <Schema>
			  <Field>
				  <FieldName>DeviceName</FieldName>
				  <FieldType>nvarchar(255)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>SubscriberLocale</FieldName>
				  <FieldType>nvarchar(10)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>SourceID</FieldName>
				  <FieldType>int</FieldType>
			  </Field>
			  <Field>
				  <FieldName>ErrorCategoryID</FieldName>
				  <FieldType>int</FieldType>
			  </Field>
			  <Field>
				  <FieldName>Station</FieldName>
				  <FieldType>nvarchar(50)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>Description</FieldName>
				  <FieldType>nvarchar(max)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>Threshold</FieldName>
				  <FieldType>int</FieldType>
			  </Field>
			  <Field>
				  <FieldName>TimeOfDayRangeBegin</FieldName>
				  <FieldType>nvarchar(50)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>TimeOfDayRangeEnd</FieldName>
				  <FieldType>nvarchar(50)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>TimeBuffer</FieldName>
				  <FieldType>nvarchar(50)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>AlarmGrouping</FieldName>
				  <FieldType>bit</FieldType>
			  </Field>
			  <Field>
				  <FieldName>GroupingTime</FieldName>
				  <FieldType>nvarchar(50)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>ElementContainer</FieldName>
				  <FieldType>nvarchar(MAX)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>AcknowledgeNotification</FieldName>
				  <FieldType>bit</FieldType>
			  </Field>
			  <Field>
				  <FieldName>SecondaryNotification</FieldName>
				  <FieldType>nvarchar(MAX)</FieldType>
			  </Field>
			  <Field>
				  <FieldName>TertiaryNotification</FieldName>
				  <FieldType>nvarchar(MAX)</FieldType>
			  </Field>
		  </Schema>
		  <ScheduledRules>
			  <ScheduledRule>
				  <RuleName>ScheduledSubscriptionsRule</RuleName>
				  <ConditionAction>
					  <SqlLogin>NSRulesEvaluator</SqlLogin>
					  <SqlUser>NSRulesEvaluator</SqlUser>
					  <InputName>NOCMonMessageEventsChronicle</InputName>
					  <SqlExpression>
						  INSERT INTO ScheduledNotifications(
						  SubscriberId,
						  DeviceName,
						  SubscriberLocale,
						  Description,
						  SourceID,
						  ErrorCategoryID,
						  Date,
						  Station,
						  Message,
						  StatusID,
						  [nUser],
						  nSubject)
						  SELECT r.[Subscription.SubscriberId],
						  r.[Subscription.DeviceName],
						  r.[Subscription.SubscriberLocale],
						  r.[Subscription.Description],
						  r.[Input.SourceID],
						  r.[Input.ErrorCategoryID],
						  r.[Input.Date],
						  r.[Input.Station],
						  r.[Input.Message],
						  r.[Input.StatusID],
						  r.[Input.nUser],
						  r.[Input.nSubject]
						  FROM ScheduledSubscriptionsRule r;
					  </SqlExpression>
				  </ConditionAction>
			  </ScheduledRule>
		  </ScheduledRules>

	  </SubscriptionClass>
  </SubscriptionClasses>

  <!-- Notification Classes -->
  <NotificationClasses>
    <NotificationClass>
      <NotificationClassName>
        MessageAlerts
      </NotificationClassName>
      <Schema>
        <Fields>
          <Field>
            <FieldName>SourceID</FieldName>
            <FieldType>int</FieldType>
          </Field>
		  <Field>
			<FieldName>Source</FieldName>
			<FieldType>varchar(max)</FieldType>
		  </Field>
		<Field>
			<FieldName>ErrorCategoryID</FieldName>
			<FieldType>int</FieldType>
		</Field>
			<Field>
				<FieldName>ErrorText</FieldName>
				<FieldType>varchar(max)</FieldType>
			</Field>
          <Field>
            <FieldName>Date</FieldName>
            <FieldType>datetime</FieldType>
          </Field>
          <Field>
            <FieldName>Station</FieldName>
            <FieldType>nvarchar(50)</FieldType>
          </Field>
          <Field>
            <FieldName>Message</FieldName>
            <FieldType>nvarchar(max)</FieldType>
          </Field>
          <Field>
            <FieldName>StatusID</FieldName>
			  <FieldType>int</FieldType>
          </Field>
			<Field>
				<FieldName>Status</FieldName>
				<FieldType>varchar(max)</FieldType>
			</Field>
		  <Field>
			<FieldName>nUser</FieldName>
			<FieldType>nvarchar(50)</FieldType>
		  </Field>
			<Field>
				<FieldName>nSubject</FieldName>
				<FieldType>nvarchar(max)</FieldType>
			</Field>
		  <Field>
			<FieldName>Description</FieldName>
			<FieldType>nvarchar(max)</FieldType>
		  </Field>
        </Fields>
      </Schema>
      <ContentFormatter>
        <ClassName>XsltFormatter</ClassName>
        <Arguments>
          <Argument>
            <Name>XsltBaseDirectoryPath</Name>
            <Value>%_AppPath_%</Value>
          </Argument>
          <Argument>
            <Name>XsltFileName</Name>
            <Value>MessageTransform.xslt</Value>
          </Argument>
        </Arguments>
      </ContentFormatter>
      <Protocols>
        <Protocol>
          <ProtocolName>SMTP</ProtocolName>
          <Fields>
            <Field>
              <FieldName>Subject</FieldName>
              <SqlExpression>'NOCMon Notification: '+CONVERT (NVARCHAR(30), GETDATE())</SqlExpression>
            </Field>
            <Field>
              <FieldName>BodyFormat</FieldName>
              <SqlExpression>'html'</SqlExpression>
            </Field>
            <Field>
              <FieldName>From</FieldName>
              <SqlExpression>'noc@captelmail.com'</SqlExpression>
            </Field>
            <Field>
              <FieldName>Priority</FieldName>
              <SqlExpression>'Normal'</SqlExpression>
            </Field>
            <Field>
              <FieldName>To</FieldName>
              <SqlExpression>DeviceAddress</SqlExpression>
            </Field>
          </Fields>
        </Protocol>
      </Protocols>
    </NotificationClass>
	  <NotificationClass>
		  <NotificationClassName>ScheduledNotifications</NotificationClassName>
		  <Schema>
			  <Fields>
				  <Field>
					  <FieldName>SourceID</FieldName>
					  <FieldType>int</FieldType>
				  </Field>
				  <Field>
					  <FieldName>ErrorCategoryID</FieldName>
					  <FieldType>int</FieldType>
				  </Field>
				  <Field>
					  <FieldName>Date</FieldName>
					  <FieldType>datetime</FieldType>
				  </Field>
				  <Field>
					  <FieldName>Station</FieldName>
					  <FieldType>nvarchar(50)</FieldType>
				  </Field>
				  <Field>
					  <FieldName>Message</FieldName>
					  <FieldType>nvarchar(max)</FieldType>
				  </Field>
				  <Field>
					  <FieldName>StatusID</FieldName>
					  <FieldType>int</FieldType>
				  </Field>
				  <Field>
					  <FieldName>nUser</FieldName>
					  <FieldType>nvarchar(50)</FieldType>
				  </Field>
				  <Field>
					  <FieldName>nSubject</FieldName>
					  <FieldType>nvarchar(max)</FieldType>
				  </Field>
				  <Field>
					  <FieldName>Description</FieldName>
					  <FieldType>nvarchar(max)</FieldType>
				  </Field>
			  </Fields>
		  </Schema>
		  <ContentFormatter>
			  <ClassName>XsltFormatter</ClassName>
			  <Arguments>
				  <Argument>
					  <Name>XsltBaseDirectoryPath</Name>
					  <Value>%_AppPath_%</Value>
				  </Argument>
				  <Argument>
					  <Name>XsltFileName</Name>
					  <Value>MessageTransform.xslt</Value>
				  </Argument>
			  </Arguments>
		  </ContentFormatter>
		  <DigestDelivery>true</DigestDelivery>
		  <Protocols>
			  <Protocol>
				  <ProtocolName>SMTP</ProtocolName>
				  <Fields>
					  <Field>
						  <FieldName>Subject</FieldName>
						  <SqlExpression>'NOCMon Notification: '+CONVERT (NVARCHAR(30), GETDATE())</SqlExpression>
					  </Field>
					  <Field>
						  <FieldName>BodyFormat</FieldName>
						  <SqlExpression>'html'</SqlExpression>
					  </Field>
					  <Field>
						  <FieldName>From</FieldName>
						  <SqlExpression>'noc@captelmail.com'</SqlExpression>
					  </Field>
					  <Field>
						  <FieldName>Priority</FieldName>
						  <SqlExpression>'Normal'</SqlExpression>
					  </Field>
					  <Field>
						  <FieldName>To</FieldName>
						  <SqlExpression>DeviceAddress</SqlExpression>
					  </Field>
				  </Fields>
			  </Protocol>
		  </Protocols>
		  <ExpirationAge>PT2H</ExpirationAge>
	  </NotificationClass>
  </NotificationClasses>

  <!-- Event Providers -->
  <Providers>
    <NonHostedProvider>
      <ProviderName>MessageSPEventProvider</ProviderName>
    </NonHostedProvider>
    <NonHostedProvider>
      <ProviderName>SQLTriggerEventProvider</ProviderName>
    </NonHostedProvider>
  </Providers>

  <!-- Generator -->
  <Generator>
    <SystemName>%_NSServer_%</SystemName>
  </Generator>

  <!-- Distributors -->
  <Distributors>
    <Distributor>
      <SystemName>%_NSServer_%</SystemName>
      <QuantumDuration>PT15S</QuantumDuration>
    </Distributor>
  </Distributors>

  <!-- ApplicationExecutionSettings -->
  <ApplicationExecutionSettings>
    <QuantumDuration>PT15S</QuantumDuration>
    <DistributorLogging>
      <LogBeforeDeliveryAttempts>false</LogBeforeDeliveryAttempts>
      <LogStatusInfo>false</LogStatusInfo>
      <LogNotificationText>false</LogNotificationText>
    </DistributorLogging>
	  <PerformanceQueryInterval>PT5S</PerformanceQueryInterval>
	  <SubscriptionQuantumLimit>1</SubscriptionQuantumLimit>
	  <ChronicleQuantumLimit>1</ChronicleQuantumLimit>
    <Vacuum>
      <RetentionAge>P1D</RetentionAge>
      <VacuumSchedule>
        <Schedule>
          <StartTime>23:00:00</StartTime>
          <Duration>P0DT02H00M00S</Duration>
        </Schedule>
      </VacuumSchedule>
    </Vacuum>
  </ApplicationExecutionSettings>

</Application>


The NOCMonMessageEvents Condition Action stored procedure looks like this:

ALTER PROCEDURE [dbo].[stp_Insert_Message_Alerts]

AS

DECLARE @matchID int

BEGIN

	SET NOCOUNT ON;

	INSERT INTO MessageAlerts(SubscriberId, DeviceName, SubscriberLocale, [Description], SourceID, Source, ErrorCategoryID, ErrorText, Date, Station, [Message], StatusID, [Status], nUser, nSubject)
	SELECT r.[Subscription.SubscriberId],
	r.[Subscription.DeviceName],
	r.[Subscription.SubscriberLocale],
	r.[Subscription.Description],
	r.[Input.SourceID],
	SRC.SourceName,
	r.[Input.ErrorCategoryID],
	ERR.ErrText,
	r.[Input.Date],
	r.[Input.Station],
	r.[Input.Message],
	r.[Input.StatusID],
	STAT.[LongDesc],
	r.[Input.nUser],
	r.[Input.nSubject]
	FROM MessageEventRule r
	INNER JOIN tblErrCategory_Sup ERR
		ON ERR.ErrorCategoryID = r.[Input.ErrorCategoryID]
	INNER JOIN tblSource_Sup SRC
		ON SRC.SourceID = r.[Input.SourceID]
	INNER JOIN tblStatus_Sup STAT
		ON STAT.StatusID = r.[Input.StatusID]

	SELECT @matchID = ErrorCategoryID 
	FROM MessageEventRule MER
	INNER JOIN ErrorMatchClearings EMATCH
		ON EMATCH.errorCategoryID = MER.[Input.ErrorCategoryID]

	IF @matchID IS NOT NULL
		BEGIN

			INSERT INTO ErrorMatches(SubscriberId, DeviceName, SubscriberLocale, [Description], SourceID, ErrorCategoryID, Date, Station, [Message], StatusID, nUser, nSubject)
			SELECT r.[Subscription.SubscriberId],
			r.[Subscription.DeviceName],
			r.[Subscription.SubscriberLocale],
			r.[Subscription.Description],
			r.[Input.SourceID],
			r.[Input.ErrorCategoryID],
			r.[Input.Date],
			r.[Input.Station],
			r.[Input.Message],
			r.[Input.StatusID],
			r.[Input.nUser],
			r.[Input.nSubject]
			FROM MessageEventRule r
			WHERE r.[Input.ErrorCategoryID] = @matchID

		END


END

The vb.net I am using to create the subscription (and I suspect this is where I’m doing something wrong?):

        Private Function GetSubscriptionData(ByRef e As Telerik.Web.UI.GridCommandEventArgs) As EventSubscription

            Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
            Dim s As New EventSubscription(EventSubscription.UserName)


            Dim svr As sqlsmo.Server = New sqlsmo.Server("MyServer")
            svr.ConnectionContext.LoginSecure = False

            svr.ConnectionContext.Login = "mylogin"
            svr.ConnectionContext.Password = "mypassword"

            Dim nocmonDB As sqlsmo.Database = svr.Databases("NOCMonMessages")
            Dim errorMatchClearings As sqlsmo.Table = nocmonDB.Tables("ErrorMatchClearings")
            Dim errorMatches As sqlsmo.Table = nocmonDB.Tables("ErrorMatches")
            Dim eventView As sqlsmo.View = nocmonDB.Views("NOCMonMessageEvents")


            Dim sourceDropDown As DropDownList = e.Item.FindControl("sourceDropdown")
            Dim errorDropDown As DropDownList = e.Item.FindControl("errorDropdown")
            Dim stationDropDown As DropDownList = e.Item.FindControl("stationDropdown")
            Dim txtDescription As TextBox = e.Item.FindControl("txtDescription")
            Dim txtThreshold As TextBox = e.Item.FindControl("txtThreshold")
            Dim txtTimeOfDayRangeBegin As TextBox = e.Item.FindControl("txtTimeOfDayRangeBegin")
            Dim txtTimeOfDayRangeEnd As TextBox = e.Item.FindControl("txtTimeOfDayRangeEnd")
            Dim txtTimeBuffer As TextBox = e.Item.FindControl("txtTimeBuffer")
            Dim txtGroupingTime As TextBox = e.Item.FindControl("txtGroupingTime")
            Dim txtElementContainer As TextBox = e.Item.FindControl("txtElementContainer")
            Dim txtSecondaryNotification As TextBox = e.Item.FindControl("txtSecondaryNotification")
            Dim txtTertiaryNotification As TextBox = e.Item.FindControl("txtTertiaryNotification")

            Dim strSource As String = sourceDropDown.SelectedItem.Value
            Dim strErrorText As String = errorDropDown.SelectedItem.Value
            Dim strStation As String = stationDropDown.SelectedItem.Text

            s.Station = strStation
            s.ErrorCategoryID = strErrorText
            s.SourceID = strSource

            Dim sourceOperator As nsr.SimpleOperator = New nsr.SimpleOperator
            Dim errorOperator As nsr.SimpleOperator = New nsr.SimpleOperator
            Dim stationOperator As nsr.SimpleOperator = New nsr.SimpleOperator

            If Trim(strSource) = "ANY" Then
                strSource = ""
                sourceOperator = Microsoft.SqlServer.NotificationServices.Rules.SimpleOperator.NotEquals
            Else
                sourceOperator = Microsoft.SqlServer.NotificationServices.Rules.SimpleOperator.Equals
            End If

            If Trim(strErrorText) = "67" Then
                strErrorText = ""
                errorOperator = Microsoft.SqlServer.NotificationServices.Rules.SimpleOperator.NotEquals
            Else
                errorOperator = Microsoft.SqlServer.NotificationServices.Rules.SimpleOperator.Equals
            End If

            If Trim(strStation) = "ANY" Then
                strStation = ""
                stationOperator = Microsoft.SqlServer.NotificationServices.Rules.SimpleOperator.NotEquals
            Else
                stationOperator = Microsoft.SqlServer.NotificationServices.Rules.SimpleOperator.Equals
            End If

If txtTimeBuffer.Text <> "00:00:00" Then Dim clearingFilter As nsr.FilterRule = New nsr.FilterRule( _ New nsr.TableInputType(nocmonDB.Tables("ErrorMatches")), _ New nsr.FilterStatement( _ New nsr.SimpleLeafCondition( _ New nsr.FieldValue("Date"), _ Microsoft.SqlServer.NotificationServices.Rules.SimpleOperator.LessThan, _ New nsr.FunctionValue(nocmonDB.UserDefinedFunctions("TIMEBUFFER", "dbo"), _ txtTimeBuffer.Text, New nsr.FieldValue("Date"))), _ Microsoft.SqlServer.NotificationServices.Rules.FilterAction.Exclude)) s.UserCondition = New nsr.AndCondition( _ New nsr.SimpleLeafCondition( _ New nsr.FieldValue("SourceID"), _ sourceOperator, strSource), _ New nsr.SimpleLeafCondition( _ New nsr.FieldValue("ErrorCategoryID"), _ errorOperator, strErrorText), _ New nsr.SimpleLeafCondition( _ New nsr.FieldValue("Station"), _ stationOperator, strStation), _ New nsr.LinkLeafCondition( _ Microsoft.SqlServer.NotificationServices.Rules.LinkLeafOperator.Any, _ clearingFilter, _ New nsr.JoinClause( _ eventView.Columns("ErrorCategoryID"), _ errorMatches.Columns("ErrorCategoryID")), _ New nsr.JoinClause( _ errorMatches.Columns("ErrorCategoryID"), _ errorMatchClearings.Columns("clearingErrorCategoryID")))) End If s.DeviceName = "myDevice" s.Locale = "en-us" s.Description = txtDescription.Text s.Threshold = txtThreshold.Text s.TimeOfDayRangeBegin = txtTimeOfDayRangeBegin.Text s.TimeOfDayRangeEnd = txtTimeOfDayRangeEnd.Text s.TimeBuffer = txtTimeBuffer.Text s.GroupingTime = txtGroupingTime.Text s.ElementContainer = txtElementContainer.Text s.SecondaryNotification = txtSecondaryNotification.Text s.TertiaryNotification = txtTertiaryNotification.Text Return s End Function

Note that where I am creating the clearingFilter, I specify ErrorMatches as the input table, yes ErrorMatches contains a field called Date, I tried changing the name of the field to fooDate, still I got the error, but updated to say could not find ‘fooDate’.

When I use the debugging stored procedures and fire the rule I get:

Msg 207, Level 16, State 1, Line 16
Invalid column name 'Date'.
Msg 207, Level 16, State 1, Line 16
Invalid column name 'Date'.

Here is the XML for the Condition:

<NSRulesObject xmlns="http://www.microsoft.com/MicrosoftNotificationServices/RulesSchema">
<Condition>
	<And>
		<SimpleLeaf Operator="=">
			<Left>
				<Field Name="SourceID" />
			</Left>
			<Right>
				<Constant Type="System.String" Value="2" />
			</Right>
		</SimpleLeaf>
		<SimpleLeaf Operator="=">
			<Left>
				<Field Name="ErrorCategoryID" />
			</Left>
			<Right>
				<Constant Type="System.String" Value="51" />
			</Right>
		</SimpleLeaf>
		<SimpleLeaf Operator="&lt;&gt;">
			<Left>
				<Field Name="Station" />
			</Left>
			<Right>
				<Constant Type="System.String" Value="" />
			</Right>
		</SimpleLeaf>
		<LinkLeaf Operator="Any">
			<FilterRule>
				<InputType>
					<Table Database="NOCMonMessages" Schema="dbo" Name="ErrorMatches" />
				</InputType>
				<Statements>
					<FilterStatement Action="Exclude">
					<Condition>
						<SimpleLeaf Operator="&lt;">
							<Left>
								<Field Name="Date" />
							</Left>
							<Right>
								<Function Db="NOCMonMessages" Schema="dbo" Name="TIMEBUFFER">
									<Parameters>
										<Constant Type="System.String" Value="5" />
										<Field Name="Date" />
									</Parameters>
								</Function>
							</Right>
						</SimpleLeaf>
					</Condition>
					</FilterStatement>
				</Statements>
			</FilterRule>
			<LinkChain>
				<JoinClause SourceDb="NOCMonMessages" SourceSchema="dbo" SourceView="NOCMonMessageEvents" SourceColumn="ErrorCategoryID" 						TargetDb="NOCMonMessages" TargetSchema="dbo" TargetView="ErrorMatches" TargetColumn="ErrorCategoryID" />
				<JoinClause SourceDb="NOCMonMessages" SourceSchema="dbo" SourceView="ErrorMatches" SourceColumn="ErrorCategoryID" 							TargetDb="NOCMonMessages" TargetSchema="dbo" TargetView="ErrorMatchClearings" TargetColumn="clearingErrorCategoryID" />
			</LinkChain>
		</LinkLeaf>
	</And>
</Condition>
</NSRulesObject>

You can see the Date field referenced in the FilterRule.

The subscription saves just fine, so this all really boils down to the rule firing error.

I hope someone can help me or point me in the right direction.

Regards,
Trevor

Describe what is not working as expected.

I have an entity called Note, and a DbSet Notes. When I try to access it via the dbContext, it throws an exception with the message «Invalid column name ‘NotificationId'».

We have an entity called Notification, which has a primary key of NotificationId, but this entity is not related to the Note entity in any way.

The Note table has no column named NotificationId, and there are no navigation properties or joins between Note and Notification.

The Note table is right before the Notification table in the database, but other than that, I can’t find any relationship between the two tables. How could this extra column be getting added to the entity in the DbContext?

I ran this in the immediate window in order to capture all of the exception details:

_dbContext.Notes.FirstOrDefault()
Microsoft.EntityFrameworkCore.Query: Warning: Query: ‘(from Note _1 in DbSet select [_1]).FirstOrDefault()’ uses First/FirstOrDefault/Last/LastOrDefault operation without OrderBy and filter which may lead to unpredictable results.
Microsoft.EntityFrameworkCore.Database.Command: Debug: Executing DbCommand [Parameters=[], CommandType=’Text’, CommandTimeout=’30’]
SELECT TOP(1) [e].[NoteId], [e].[ActiveFlag], [e].[CreateDate], [e].[CreateUserId], [e].[Description], [e].[NotificationId], [e].[SecurityFilter], [e].[Title], [e].[UpdateDate], [e].[UpdateUserId]
FROM [Note] AS [e]
WHERE [e].[ActiveFlag] = 1
Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (7ms) [Parameters=[], CommandType=’Text’, CommandTimeout=’30’]
SELECT TOP(1) [e].[NoteId], [e].[ActiveFlag], [e].[CreateDate], [e].[CreateUserId], [e].[Description], [e].[NotificationId], [e].[SecurityFilter], [e].[Title], [e].[UpdateDate], [e].[UpdateUserId]
FROM [Note] AS [e]
WHERE [e].[ActiveFlag] = 1

System.Data.SqlClient.SqlException (0x80131904): Invalid column name ‘NotificationId’.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues) ClientConnectionId:01e5c025-ae4f-44d6-8b58-67e63f6577df Error Number:207,State:1,Class:16 Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'WinsApp.Infrastructure.Data.WinsAppContext'. System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'NotificationId'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
ClientConnectionId:01e5c025-ae4f-44d6-8b58-67e63f6577df
Error Number:207,State:1,Class:16

System.Data.SqlClient.SqlException (0x80131904): Invalid column name ‘NotificationId’.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()
ClientConnectionId:01e5c025-ae4f-44d6-8b58-67e63f6577df
Error Number:207,State:1,Class:16
Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type ‘WinsApp.Infrastructure.Data.WinsAppContext’.
System.Data.SqlClient.SqlException (0x80131904): Invalid column name ‘NotificationId’.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable1 source) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_11.b__0(QueryContext qc)
ClientConnectionId:01e5c025-ae4f-44d6-8b58-67e63f6577df
Error Number:207,State:1,Class:16

System.Data.SqlClient.SqlException (0x80131904): Invalid column name ‘NotificationId’.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable1 source) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_11.b__0(QueryContext qc)
ClientConnectionId:01e5c025-ae4f-44d6-8b58-67e63f6577df
Error Number:207,State:1,Class:16
‘_dbContext.Notes.FirstOrDefault()’ threw an exception of type ‘System.Data.SqlClient.SqlException’
Class: 16
ClientConnectionId: {01e5c025-ae4f-44d6-8b58-67e63f6577df}
Data: {System.Collections.ListDictionaryInternal}
ErrorCode: -2146232060
Errors: {System.Data.SqlClient.SqlErrorCollection}
HResult: -2146232060
HelpLink: null
InnerException: null
LineNumber: 1
Message: «Invalid column name ‘NotificationId’.»
Number: 207
Procedure: «»
Server: «(local)»
Source: «.Net SqlClient Data Provider»
StackTrace: » at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)rn at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)rn at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)rn at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()rn at System.Data.SqlClient.SqlDataReader.get_MetaData()rn at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)rn at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 t imeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)rn at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)rn at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)rn at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)rn at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)rn at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)rn at Microsoft.EntityFrameworkCore.Quer
y.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)rn at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded)rn at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()rn at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)rn at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator()rn at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext()rn at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()rn at System.Linq.Enumerable.First[TSource](IEnumerable1 source)rn at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_11.b__0(QueryContext qc)»
State: 1
TargetSite: {Void OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action])}

Further technical details

EF Core version: 2.2
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10 64 bit
IDE: Visual Studio 2017 latest build

image

SQL Server 2008 Enterprise SQL Server 2008 Developer SQL Server 2008 Standard SQL Server 2008 Standard Edition for Small Business SQL Server 2008 Workgroup SQL Server 2008 R2 Developer SQL Server 2008 R2 Enterprise SQL Server 2008 R2 Standard SQL Server 2008 R2 Workgroup More…Less

Microsoft distributes Microsoft SQL Server 2008 and Microsoft SQL Server 2008 R2 fixes as one downloadable file. Because the fixes are cumulative, each new release contains all the hotfixes and all the security fixes that were included with the previous SQL Server 2008 or SQL Server 2008 R2 fix release.

Symptoms

When you run a linked server query from one instance of Microsoft SQL Server 2008 or SQL Server 2008 R2 to another instance of SQL Server, the query fails, and you receive an error message that resembles the following:

Msg 8180, Level 16, State 1, Line 1
Statement(s) could not be prepared.

Msg 4104, Level 16, State 1, Line 1

The multi-part identifier «<column name>» could not be bound.
Msg 207, Level 16, State 1, Line 1
Invalid column name ‘<column name>‘.

Cause

This issue occurs because some columns are incorrectly included in the linked server query. However, these columns are not in the linked server table. Therefore, the query fails.

Note To display information about each statement of the linked server query, use the SET SHOWPLAN_ALL or SET SHOWPLAN_XML setting. To determine whether the query is incorrectly formed, check the Remote Query section of the SET SHOWPLAN_ALL or SET SHOWPLAN_XML setting output.

Resolution

SQL Server 2008 Service Pack 1

The fix for this issue was first released in Cumulative Update 10 for SQL Server 2008 Service Pack 1. For more information about this cumulative update package, click the following article number to view the article in the Microsoft Knowledge Base:

2279604 Cumulative update package 10 for SQL Server 2008 Service Pack 1Note Because the builds are cumulative, each new fix release contains all the hotfixes and all the security fixes that were included with the previous SQL Server 2008 fix release. Microsoft recommends that you consider applying the most recent fix release that contains this hotfix. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

970365 The SQL Server 2008 builds that were released after SQL Server 2008 Service Pack 1 was released Microsoft SQL Server 2008 hotfixes are created for specific SQL Server service packs. You must apply a SQL Server 2008 Service Pack 1 hotfix to an installation of SQL Server 2008 Service Pack 1. By default, any hotfix that is provided in a SQL Server service pack is included in the next SQL Server service pack.

SQL Server 2008 Service Pack 2

The fix for this issue was first released in Cumulative Update 1 for SQL Server 2008 Service Pack 2. For more information about this cumulative update package, click the following article number to view the article in the Microsoft Knowledge Base:

2289254 Cumulative update 1 for SQL Server 2008 Service Pack 2Note Because the builds are cumulative, each new fix release contains all the hotfixes and all the security fixes that were included with the previous SQL Server 2008 fix release. We recommend that you consider applying the most recent fix release that contains this hotfix. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

2402659 The SQL Server 2008 builds that were released after SQL Server 2008 Service Pack 2 was released

SQL Server 2008 R2


The fix for this issue was first released in Cumulative Update 5. For more information about how to obtain this cumulative update package for SQL Server 2008 R2, click the following article number to view the article in the Microsoft Knowledge Base:

2438347 Cumulative Update package 5 for SQL Server 2008 R2 Note Because the builds are cumulative, each new fix release contains all the hotfixes and all the security fixes that were included with the previous SQL Server 2008 R2 fix release. We recommend that you consider applying the most recent fix release that contains this hotfix. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

981356 The SQL Server 2008 R2 builds that were released after SQL Server 2008 R2 was released

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section.

References

For more information about the SET SHOWPLAN_XML setting, visit the following Microsoft Developer Network (MSDN) website:

General information about the «SET SHOWPLAN_XML» settingFor more information about the SET SHOWPLAN_ALL setting, visit the following MSDN website:

935897 An Incremental Servicing Model is available from the SQL Server team to deliver hotfixes for reported problems

For more information about the naming schema for SQL Server updates, click the following article number to view the article in the Microsoft Knowledge Base:

822499New naming schema for Microsoft SQL Server software update packagesFor more information about software update terminology, click the following article number to view the article in the Microsoft Knowledge Base:

824684 Description of the standard terminology that is used to describe Microsoft software updates

Need more help?

alter  procedure test 
(
 @t1 varchar(50),
 @emp_id  varchar(15),
 @dept_id varchar(15),
 @emp_name varchar(50),
 @emp_status varchar(10)
)
 as
 begin
 
 DECLARE @SQL varchar(250)
 
 SELECT @SQL = 'insert into ' + @t1 + ' values ('+@emp_id+','+@dept_id+','+@emp_name+','+@emp_status+')'
 
 EXEC (@SQL)
    
 end 

exec test ‘Tbl_101_Employee_Creation’,’E-00001′,’D-001′,’kiran’,’Active’

ERROR

Msg 207, Level 16, State 1, Line 1
Invalid column name 'E'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'D'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'kiran'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Active'.

[edit]Code block added[/edit]


Alter procedure test 
(
@t1 varchar(50),
@emp_id varchar(15),
@dept_id varchar(15),
@emp_name varchar(50),
@emp_status varchar(10)
 
)
as
begin

DECLARE @SQL varchar(250)

SELECT @SQL = 'insert into ' + @t1 + ' values ('''+@emp_id+''','''+@dept_id+''','''+@emp_name+''','''+@emp_status+ ')'

print  (@SQL)

end 

you can use parameter freely without any single codes. like below..
alter procedure test
(
@t1 varchar(50),
@emp_id varchar(15),
@dept_id varchar(15),
@emp_name varchar(50),
@emp_status varchar(10)

)
as
begin

DECLARE @SQL varchar(250)

SELECT @SQL = ‘insert into @t1 values (@emp_id,@dept_id,@emp_name,@emp_status)’

EXEC (@SQL)

end

Alter procedure test 
(
@t1 varchar(50),
@emp_id varchar(15),
@dept_id varchar(15),
@emp_name varchar(50),
@emp_status varchar(10)
 
)
as
begin
 
DECLARE @SQL varchar(250)
 
SELECT @SQL = 'insert into ' + @t1 + ' values ('''+@emp_id+''','''+@dept_id+''','''+@emp_name+''','''+@emp_status+ ''')'
 
EXEC  (@SQL)
 
end 

hi
I do also get the same error
from below code , could anyone please tell me what I am doing wrong ?

go
;with cte as(
select row_number()over(partition by date order by ID)ID,
Bussiness,Date, Value 
from mytable
)
SELECT *
FROM cte
PIVOT (
	MAX([Value])
	FOR Date IN ( [Nov-18],[Dec-18])
) AS pvt

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Talinka

74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

1

Тип сущности требует определения первичного ключа, но ключа в бд нет

30.09.2020, 06:44. Показов 1528. Ответов 25

Метки нет (Все метки)


Здравствуйте, делаю сайт и столкнулась с рядом трудностей, которых в прошлых раз не было.

Во-первых, не работает Scaffold-DbContext, пишет, что недопустимые столбцы, которых в принципе нет в таблицах.
Во-вторых, создала уже все вручную, решила добавить представление, но выпадала сначала ошибка с пакетом, якобы сбой.
Пересоздала все с нуля, вновь пытаюсь добавить представление, вылетает новая ошибка: The entity type ‘SprCost’ requires a primary key to be defined.
самый сок в том, что я не увидела ключа в данной таблице.

SQL
1
2
3
4
5
6
7
CREATE TABLE Test.dbo.SprCost (
  TYPE INT NULL,
  cost INT NULL,
  YEAR INT NULL
)
ON [PRIMARY]
GO

Помогите пожалуйста

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт .NET

11075 / 7640 / 1179

Регистрация: 21.01.2016

Сообщений: 28,687

30.09.2020, 06:59

2

Цитата
Сообщение от Talinka
Посмотреть сообщение

самый сок в том, что я не увидела ключа в данной таблице.

Так добавьте и он вам станет виден.



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

30.09.2020, 07:23

 [ТС]

3

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

Добавлено через 16 минут
Там просто небольшой справочник, без id



0



Эксперт .NET

11075 / 7640 / 1179

Регистрация: 21.01.2016

Сообщений: 28,687

30.09.2020, 08:22

4

Цитата
Сообщение от Talinka
Посмотреть сообщение

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

Если можете запросы выполнять, то и базу редактировать можете.

Цитата
Сообщение от Talinka
Посмотреть сообщение

Там просто небольшой справочник, без id

А как вы собрались на записи из этого справочника ссылаться без ключа?



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

30.09.2020, 09:00

 [ТС]

5

Цитата
Сообщение от Usaga
Посмотреть сообщение

А как вы собрались на записи из этого справочника ссылаться без ключа?

Таблица имеет 3 столбца, без ключей. Справочник просто пополняется или записи удаляются. Он нигде больше не участвует. Он просто есть. По крайней мере так сделано в программе, которую мне нужно перевести в вэб приложение.



0



2955 / 2121 / 615

Регистрация: 02.08.2011

Сообщений: 5,852

30.09.2020, 09:13

6

Цитата
Сообщение от Talinka
Посмотреть сообщение

Она сделана давно,а значит и ключа там не должно быть

Интересный вывод.

Если база была сделана давно, это не отменяет возможности того, чтобы она была спроектирована через одно место.
Текст ошибки вам об этом и говорит:

the entity type ‘SprCost’ requires a primary key to be defined.

Не бойтесь изменять схему, просто добавьте PK, и все заработает.



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

30.09.2020, 09:20

 [ТС]

7

Цитата
Сообщение от IamRain
Посмотреть сообщение

Если база была сделана давно, это не отменяет возможности того, чтобы она была спроектирована через одно место.

Возможно и так, но как я сказала у меня нет доступа на редактирование. Приходится иметь дело с тем, что есть.
ну и опять же понятно, почему вылетала ошибка о недопустимых столбцах при использовании Scaffold-DbContext, учитывая, что столбцов с таким именем просто нет



0



2955 / 2121 / 615

Регистрация: 02.08.2011

Сообщений: 5,852

30.09.2020, 09:25

8

Наличие PK — это обязательное условие, и типичные справочники — это таблицы, в которых, чаще всего 2-3 столбца, один из которых всегда PK. Ну никак по-другому, тогда просто смиритесь, у вас не получится сделать Scaffold с этой таблицы.



0



Эксперт .NET

11075 / 7640 / 1179

Регистрация: 21.01.2016

Сообщений: 28,687

30.09.2020, 09:34

9

Talinka, если у вас Entity Framework Core 2.1 или новее, то вы можете использовать Keyless Entitites.

Добавлено через 1 минуту
Но я бы рекомендовал завести первичный ключ в таблице и не парться.



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

30.09.2020, 09:50

 [ТС]

10

Цитата
Сообщение от Usaga
Посмотреть сообщение

вы можете использовать Keyless Entitites

Вообще, да, 2.1, но [Keyless] не работает



0



Usaga

Эксперт .NET

11075 / 7640 / 1179

Регистрация: 21.01.2016

Сообщений: 28,687

30.09.2020, 09:57

11

Talinka, ну, там написано, что оно с атрибутом только в 5.0, а ранее как-то иначе называлось. Попробуйте вариант с Fluent:

C#
1
2
3
4
5
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<BlogPostsCount>()
        .HasNoKey(); // вот это
}

Если и это не получится, то либо добавляйте первичный ключ, либо не судьба с EF Core это сделать, пока 5.0 не вышел.



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

30.09.2020, 10:04

 [ТС]

12

Цитата
Сообщение от Usaga
Посмотреть сообщение

Попробуйте вариант с Fluent

Так тоже сразу эе попробовала. Видимо не судьба



0



Эксперт .NET

11075 / 7640 / 1179

Регистрация: 21.01.2016

Сообщений: 28,687

30.09.2020, 10:08

13

Talinka, значит для работы с этой сущностью используйте Dapper или Linq2Db. Им пофигу на ключи. А когда выйдет EF Core 5.0, то сделаете уже его силами. Или попросите того, у кого есть доступ к базе, чтобы первичный ключ добавили в таблицу. Это не так фича на которой можно что-то сэкономить.



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

05.10.2020, 05:28

 [ТС]

14

Цитата
Сообщение от IamRain
Посмотреть сообщение

у вас не получится сделать Scaffold с этой таблицы

Я создала базу с нуля, добавила ключи, однако scaffold не работает. Пишет:
Error Number:207,State:1,Class:16
Недопустимое имя столбца «has_filter».
Недопустимое имя столбца «filter_definition».

А у меня нет таких столбцов



0



Эксперт .NET

11075 / 7640 / 1179

Регистрация: 21.01.2016

Сообщений: 28,687

05.10.2020, 10:37

15

Talinka, гугление названий этих столбцов говорит о том, что они принадлежат системной таблице SQL Server’а. У вас SQL Server какой версии? Что-то древнее и мхом покрытое?



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

05.10.2020, 10:39

 [ТС]

16

я тоже нашла что это системное, только не понятно почему

программа вроде 2018 года, не должна еще мхом зарасти



0



Эксперт .NET

11075 / 7640 / 1179

Регистрация: 21.01.2016

Сообщений: 28,687

05.10.2020, 10:41

17

Какая программа? SQL Server какой версии? В 2018-м SQL Server не релизился.



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

06.10.2020, 09:40

 [ТС]

18

Цитата
Сообщение от Usaga
Посмотреть сообщение

Какая программа?

dbForge

Цитата
Сообщение от Usaga
Посмотреть сообщение

SQL Server какой версии

5.6 как я поняла



0



Эксперт .NET

11075 / 7640 / 1179

Регистрация: 21.01.2016

Сообщений: 28,687

06.10.2020, 09:54

19

Talinka, википедия говорит, что такой версии SQL Server’а никогда не было. А если бы была, то в районе 1994-го года. Вы версию чего вообще смотрите?

В любом случае, ошибка с недопустимыми именами столбцов может быть из-за слишком старой версии SQL Server’а.



0



74 / 6 / 0

Регистрация: 24.01.2020

Сообщений: 159

06.10.2020, 10:01

 [ТС]

20

просто странно, что после создания в ручную, все работает

Спасибо вам за ответы!



0



  • Our
  • Forum
  • Getting Started
  • Installing umbraco

Press Ctrl / CMD + C to copy this to your clipboard.

Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Joseph

    32 posts

    146 karma points

    Dec 17, 2015 @ 13:46

    Joseph

    Hi all,

    Been attempting to upgrade a client website from 7.2.8 to 7.3.4 using nuget. While the packages update fine and the solution builds we are having issues on the installer screen when booting into the website to complete the update.

    Once you click to proceed update on the site you get an error stating an error during installation, then the following in the logs:

    Error Number:207,State:1,Class:16
    2015-12-17 13:28:38,375 [P4100/D2/T8] WARN Umbraco.Core.Services.UserService — An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored. Exception: System.Data.SqlClient.SqlException (0x80131904): Invalid column name ‘securityStampToken’.
    Invalid column name ‘lastLoginDate’.
    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
    at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
    at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
    at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
    at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
    at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource
    1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
    at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
    at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
    at Umbraco.Core.Persistence.PetaPocoCommandExtensions.<>c__DisplayClass1.<ExecuteNonQueryWithRetry>b__0()
    at Umbraco.Core.Persistence.FaultHandling.RetryPolicy.ExecuteAction[TResult](Func
    1 func)
    at Umbraco.Core.Persistence.Database.Update(String tableName, String primaryKeyName, Object poco, Object primaryKeyValue, IEnumerable1 columns)
    at Umbraco.Core.Persistence.Database.Update(Object poco, Object primaryKeyValue, IEnumerable
    1 columns)
    at Umbraco.Core.Persistence.Repositories.UserRepository.PersistUpdatedItem(IUser entity)
    at Umbraco.Core.Persistence.Repositories.RepositoryBase2.PersistUpdatedItem(IEntity entity)
    at Umbraco.Core.Persistence.UnitOfWork.PetaPocoUnitOfWork.Commit(Action
    1 transactionCompleting)
    at Umbraco.Core.Services.UserService.Save(IUser entity, Boolean raiseEvents)
    ClientConnectionId:57392c19-3e7d-4806-8599-8c81ebce0de2

    …So, from my end it appears that I am missing some database user table rows, but the reason for this is unclear. Is there a specific interim version which includes / generates these rows as part of the updater which is not included?

    VS2013 solution if that has any impact. Any help appreciated…

  • Sebastiaan Janssen

    Those are added for 7.3.0. But they should also be added when just upgrading to 7.3.4.

    Just to make sure: when you upgrade, you should not change umbracoConfigurationStatus in your web.config, it should have a value of 7.2.8.
    Also, don’t change anything to your connection string, it should point to the database where Umbraco is currently installed (your 7.2.8 database).

    Also make sure that all files are copied over, maybe start by deleting (moving out) all of the files in your bin folder and doing a rebuild of your project in Visual Studio. See if that makes a difference.

  • Joseph

    32 posts

    146 karma points

    Dec 17, 2015 @ 15:39

    Joseph

    Hi Sebastiaan,

    The web config should have been left intact in this instance and was not removed, ditto for the connection string.

    Since posting attempted an upgrade on a personal project of mine without issue, so thinking it is something specific to this particular project. Thinking the solution should be fine with the database configs as it got far enough into the process to identify individual table columns were not present so it must have connected at least.

    Will keep plugging away this end and see if I can narrow it down. Thanks for getting back to me.

  • Joseph

    32 posts

    146 karma points

    Dec 21, 2015 @ 11:34

    Joseph

    Hi all,

    Making no progress on this one. Everything appears to be fine in terms of the solution. The main issue seems to be in the creation of these user table rows.

    Is there any way to kick-off a process to perform just that section of the install to ensure those rows get created, or any issue in me cloning / replicating the table structure from another updated project of the same version for the UmbracoUser table?

    Ran through the process from scratch from my pre-update code, and ensured all installation instructions were followed — no removal of the version in web.config etc…

  • Sebastiaan Janssen

    Can you send me your zipped VS solution + database so I can help and possibly fix if the problem is in Umbraco? A DropBox / WeTransfer link can be sent to [email protected]

    Thanks!

  • Joseph

    32 posts

    146 karma points

    Dec 21, 2015 @ 13:20

    Joseph

    @Sebastiaan, I would have to get client / business approval first. They may be willing for us to do this, but our main contacts are unavailable for the next week or two due to the holidays.

    Will ask and provide if possible, and in the interim backup + clone the DB locally and try copying across the structure from a successful upgrade to see if that will help the update go through.

  • Keith R Hubbard

    @Sebastiaan I had a simple site upgrade from 7.2.8 and tried to go to 7.3.4 and it failed. I have tried manual and nuget and get the same result. Frontend is blank with unknown error and the backend is all still there. I am now just rebuilding the site in 7.3.4.

  • Ben

    107 posts

    373 karma points

    Jan 12, 2016 @ 22:00

    Ben

    When I upgraded to v7.3.4, from v7.2.8, I found that I had to go to v7.3.0 first. Although, I am doing it manually, so maybe I messed it up the first time I tried to upgrade it.

  • Allan

    2 posts

    73 karma points

    Jan 14, 2016 @ 22:40

    Allan

    Hi Keith,

    Do you have a solution to your issue? I am having the same problem.

  • Dan Evans

    628 posts

    1015 karma points

    Feb 04, 2016 @ 07:34

    Dan Evans

    I’m getting the same error when trying to upgrade from 7.2.6 > 7.3.6

  • Dan Evans

    628 posts

    1015 karma points

    Feb 04, 2016 @ 07:46

    Dan Evans

    This is the specific error we are getting:

    2016-02-04 07:21:42,874 [28] WARN Umbraco.Core.Services.UserService — An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored. Exception: System.Data.SqlClient.SqlException (0x80131904): Invalid column name ‘securityStampToken’.
    Invalid column name ‘lastLoginDate’.

    I upgraded the staging DB on this site successfully but the live DB returns this error.

  • Kieran Harvey

    did anyone one else figure this out. I am also stuck.
    BOTH

    • 7.2.1 => 7.3.0
    • 7.2.1 => 7.4.1

    I am looking at doing a schema compare and see manually doing that step will help

    Umbraco.Core.Services.UserService - An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored. 
    Exception: System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'securityStampToken'.  Invalid column name 'lastLoginDate'.
    

    ERROR UmbracoExamine.DataServices.UmbracoLogService - Provider=InternalMemberIndexer, NodeId=-1 System.Exception: Cannot index queue items, the index doesn't exist!,, IndexSet: InternalMemberIndexSet
    
     2016-02-18 14:41:52,385 [P8640/D3/T24] ERROR UmbracoExamine.DataServices.UmbracoLogService - Provider=InternalIndexer, NodeId=-1 System.Exception: Cannot index queue items, the index doesn't exist!,, IndexSet: InternalIndexSet
     2016-02-18 14:41:52,385 [P8640/D3/T24] ERROR UmbracoExamine.DataServices.UmbracoLogService - Provider=ExternalIndexer, NodeId=-1 System.Exception: Cannot index queue items, the index doesn't exist!,, IndexSet: ExternalIndexSet
     2016-02-18 14:42:22,402 [P8640/D3/T24] INFO  Umbraco.Core.UmbracoApplicationBase - Application shutdown. Details: ConfigurationChange
    

  • Kieran Harvey

    Getting a new project with correct DB schema then doing a schema compare and update on the target seemed to work.

  • Dan Evans

    628 posts

    1015 karma points

    Feb 18, 2016 @ 12:33

    Dan Evans

    I was planning to give the upgrade direct to 7.4 a go but will hold off now. Interested to hear if you find a resolution to this.

  • Angel Stubbings

    I am also having this problem when upgrading from 7.2.6 > 7.4.1

    2016-02-18 12:40:00,462 [P3092/D2/T8] ERROR Umbraco.Core.Persistence.UmbracoDatabase - Database exception occurred
    System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'securityStampToken'.
    Invalid column name 'lastLoginDate'.
    

  • Kurt

    29 posts

    111 karma points

    Mar 07, 2016 @ 20:36

    Kurt

    I’m getting the same error as Angel and Kieran when trying to upgrade from 7.2.8 to 7.4.1. Has anyone figured out a resolution to this (short of doing a complete manual schema compare as Kieran did)?

  • Boris

    1 post

    21 karma points

    Mar 16, 2016 @ 23:11

    Boris

    I have been trying to upgrade Umbraco from version 6.1.6 to 7.4.1 and i ran into the mentioned problem. I have compared clean Umbraco 7 installation with an upgraded version (6.1.6 -> 7.4.1) and i have noticed that membership providers in web.config have not been updated.

    Clean Umbraco 7.4.1:

    <add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="8" useLegacyEncoding="true" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" passwordFormat="Hashed" />
    

    Updated 6.1.6 to 7.4.1

    <add name="UsersMembershipProvider" type="umbraco.providers.UsersMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" />
    

    Apart from different type, few attributes are missing. Upon updating these values in web.config i have been able to log in and complete database upgrade.

    Hope this helps.

  • Paul Stephenson

    I have had a similar problem, but this error was a red herring.

    Like @Dan Evans above, I successfully upgraded development and staging sites to 7.4.1 (from 7.2.2), but then when running the same process on the live DB I got the error:

     2016-03-21 08:03:08,108 [P5736/D2/T12] INFO  Umbraco.Core.Security.BackOfficeSignInManager - Event Id: 0, state: User: ****** logged in from IP address **.**.**.**
     2016-03-21 08:03:08,155 [P5736/D2/T12] ERROR Umbraco.Core.Persistence.UmbracoDatabase - Database exception occurred
    System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'securityStampToken'.
    Invalid column name 'lastLoginDate'.
       at [...stacktrace...]
    Error Number:207,State:1,Class:16
     2016-03-21 08:03:08,171 [P5736/D2/T12] WARN  Umbraco.Core.Services.UserService - An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored. Exception: System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'securityStampToken'.
    Invalid column name 'lastLoginDate'.
       at [...stacktrace...]
    

    I checked the logs from the staging server, and they also had these errors, but the server had upgraded and run fine! Notice the line «normally this warning can be ignored».

    In my case there was a further error just afterwards:

    Error Number:207,State:1,Class:16
     2016-03-21 08:03:09,999 [P5736/D2/T11] ERROR Umbraco.Core.UmbracoApplicationBase - An unhandled exception occurred
    System.Web.HttpCompileException (0x80004005): [...path...]umbracoInstallViewsIndex.cshtml(9): error CS0103: The name 'ViewBag' does not exist in the current context
    

    This was the real problem. It was caused by a new Web.config file in umbracoInstallViews that was put there by the Umbraco 7.4 install from NuGet (Stack Overflow answer). Our custom deployment script to live sites ignores Web.config files because they often need generating specially for each server, but I didn’t notice this new one so didn’t put anything in place to create it.

    To those of you experiencing this securityStampToken error, I urge you to look further down your log file!

  • Joseph

    32 posts

    146 karma points

    May 24, 2016 @ 15:36

    Joseph

    Hi all,

    Had to pick up this upgrade again and encountered the same issue. It looks like many column name fields are not being created correctly on update…

    To recap — previously I was attempting v7.2.8 to 7.3.4. On this attempt I took it back a step so I could go to the next stable release after 7.2.8. As such since 7.3.0 had Nuget issues the next stable version was seemingly 7.3.1.

    • As an aside, should a release with faults of that nature in a version not be flagged on the affected version with a note to go to the next stable release? Would not have known to check and only found out by fortune… Ditto if it has a known security issue for example.

    A comparison in the DB’s against my upgraded site vs a new site showed that the following columns were missing from the dbo.umbracoUser table:

    • securityStamptoken
    • failedLoginAttempts
    • lastLockoutdate
    • lastPasswordChangeDate
    • lastLoginDate

    To me, this looks like something that should be added in the update process is missing relating to adding these columns to the database for user management. I saw config amends related to OWIN which could maybe be a factor, but is speculation.

    Regardless, do we know what version of Umbraco introduced these DB fields and potential suggestions on how to rectify please?

  • Sebastiaan Janssen

    We do everything we can to make upgrades as smooth as possible.

    I suspect what happened is that you’ve updated the version number in web.config to 7.3.0 or higher manually, which means the migrations for 7.3.0 didn’t run. This is when those properties were introduced. You can simply set the version in web.config to 7.2.8 right now and run through the upgrade installer again, the properties will then be created for you.

    As an aside: when upgrading, we always recommend going to the latest version so you don’t run into security issues for example.

  • Sebastiaan Janssen

  • Joseph

    32 posts

    146 karma points

    May 24, 2016 @ 16:01

    Joseph

    Hi Sebastiaan,

    The web config on this branch has always been at 7.2.8 and has not been manually modified. The latest post for me above was on a clean 7.2.8 branch, which then had a Nuget package update to 7.3.0 (and then subsequently 7.3.1 when spotting the issues noted in 7.3.0).

    The Post Install step of this then fails when trying to authorise the upgrade.

  • Sebastiaan Janssen

    I don’t understand what you mean? What fails? What did you do (steps)? What do you see? What’s the error message? :)

  • Sebastiaan Janssen

    This is what it looks like for me to upgrade from 7.2.8 to 7.3.1, make sure to skip around in it because some things take a little long.

    Note that I say NO to overwriting config files at 2:43 and that I run a build at 3:08 after which the video gets a bit more exciting.

    https://www.youtube.com/watch?v=JEBS045p5fI&feature=youtu.be

    I have the following log messages as well, showing what it tried to do.

    What’s different in your upgrade?

     2016-05-24 18:14:02,692 [P24372/D13/T65] INFO  Umbraco.Core.Persistence.Migrations.MigrationRunner - Executing sql statement 32: ALTER TABLE [umbracoUser] ADD [securityStampToken] NVARCHAR(255) NULL
    
     2016-05-24 18:14:02,695 [P24372/D13/T65] INFO  Umbraco.Core.Persistence.Migrations.MigrationRunner - Executing sql statement 33: ALTER TABLE [umbracoUser] ADD [failedLoginAttempts] INTEGER NULL
    
     2016-05-24 18:14:02,695 [P24372/D13/T65] INFO  Umbraco.Core.Persistence.Migrations.MigrationRunner - Executing sql statement 34: ALTER TABLE [umbracoUser] ADD [lastLockoutDate] DATETIME NULL
    
     2016-05-24 18:14:02,696 [P24372/D13/T65] INFO  Umbraco.Core.Persistence.Migrations.MigrationRunner - Executing sql statement 35: ALTER TABLE [umbracoUser] ADD [lastPasswordChangeDate] DATETIME NULL
    
     2016-05-24 18:14:02,697 [P24372/D13/T65] INFO  Umbraco.Core.Persistence.Migrations.MigrationRunner - Executing sql statement 36: ALTER TABLE [umbracoUser] ADD [lastLoginDate] DATETIME NULL
    

  • Joseph

    32 posts

    146 karma points

    May 24, 2016 @ 16:44

    Joseph

    Hi Sebastiaan,

    Firstly thanks for taking the time to record the process… Mine was pretty much the same to be honest.

    Started off at 7.2.8, did a Nuget update to 7.3.0 and a corresponding update to Umbraco.Core 7.3.0 for any class libraries that required it due to references. If the config option appeared we entered no.

    Built the project and booted, had an issue with some System.Web.Http references. At this stage I have not gotten to the authorise upgrade point due to a yellow screen on those references. Noticed the notes on 7.3.1, and repeated the process with 7.3.1.

    After updating to 7.3.1 I did a rebuild and opened my site. The yellow screens had gone, and the authorise upgrade login was presented.

    enter image description here

    Chrome inspector showed the failed request:

    enter image description here

    Just going to dig out the trace log, comment again in a sec…

  • Sebastiaan Janssen

    First of all: at this point I recommend you just upgrade to 7.4.3, there’s no reason to stick with 7.3 and certainly no reason to do upgrades version by version, you can go straight from 7.2.8 to 7.4.3.

    Thanks for the error, you might have conflicting rewrite rules: http://issues.umbraco.org/issue/U4-5019

  • Ryan Brown

    I watched your video and tried to duplicate it. I was able to perform an upgrade from 7.1.6 to 7.4.3 and, with a bit of tweaking to various config files, get it to build. However, when I got to the login page, I’m unable to login. Login Problems

    Checking the logs I see:

    WARN  Umbraco.Core.Services.UserService - An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored.
    Exception: System.Data.SqlClient.SqlException (0x80131904):
    Invalid column name 'securityStampToken'.
    Invalid column name 'failedLoginAttempts'.
    

    I cannot proceed with the upgrade because I cannot log in. It seems pretty clear that there’s some break in the upgrade process which is putting the database and authentication code in a mismatched state. What should I do to attempt to resolve this issue?

  • Joseph

    32 posts

    146 karma points

    May 24, 2016 @ 16:48

    Joseph

    Unfortunately no idea how to format the following nicely in the editor — apologies…

    ----------
    2016-05-24 17:36:20,063 [P8740/D2/T10] INFO  Umbraco.Core.Persistence.UmbracoDatabase -    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
       at System.Data.SqlClient.SqlDataReader.get_MetaData()
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
       at Umbraco.Core.Persistence.Database.<Query>d__7`1.MoveNext()
     2016-05-24 17:36:24,014 [P8740/D2/T9] INFO  Umbraco.Core.Security.BackOfficeSignInManager - Event Id: 0, state: Login attempt succeeded for username admin from IP address 127.0.0.1
     2016-05-24 17:36:24,686 [P8740/D2/T9] INFO  Umbraco.Core.Persistence.UmbracoDatabase -    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at StackExchange.Profiling.Data.ProfiledDbCommand.ExecuteNonQuery() in c:CodegithubSamSaffronMiniProfilerStackExchange.ProfilingDataProfiledDbCommand.cs:line 279
       at Umbraco.Core.Persistence.PetaPocoCommandExtensions.<>c__DisplayClass1.<ExecuteNonQueryWithRetry>b__0()
       at Umbraco.Core.Persistence.FaultHandling.RetryPolicy.ExecuteAction[TResult](Func`1 func)
       at Umbraco.Core.Persistence.Database.Update(String tableName, String primaryKeyName, Object poco, Object primaryKeyValue, IEnumerable`1 columns)
     2016-05-24 17:36:24,826 [P8740/D2/T9] WARN  Umbraco.Core.Services.UserService - An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored. Exception: System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'securityStampToken'.
    Invalid column name 'lastLoginDate'.
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at StackExchange.Profiling.Data.ProfiledDbCommand.ExecuteNonQuery() in c:CodegithubSamSaffronMiniProfilerStackExchange.ProfilingDataProfiledDbCommand.cs:line 279
       at Umbraco.Core.Persistence.PetaPocoCommandExtensions.<>c__DisplayClass1.<ExecuteNonQueryWithRetry>b__0()
       at Umbraco.Core.Persistence.FaultHandling.RetryPolicy.ExecuteAction[TResult](Func`1 func)
       at Umbraco.Core.Persistence.Database.Update(String tableName, String primaryKeyName, Object poco, Object primaryKeyValue, IEnumerable`1 columns)
       at Umbraco.Core.Persistence.Database.Update(Object poco, Object primaryKeyValue, IEnumerable`1 columns)
       at Umbraco.Core.Persistence.Repositories.UserRepository.PersistUpdatedItem(IUser entity)
       at Umbraco.Core.Persistence.Repositories.RepositoryBase`2.PersistUpdatedItem(IEntity entity)
       at Umbraco.Core.Persistence.UnitOfWork.PetaPocoUnitOfWork.Commit(Action`1 transactionCompleting)
       at Umbraco.Core.Services.UserService.Save(IUser entity, Boolean raiseEvents)
    ClientConnectionId:0292c6b4-f5c4-4519-b026-622ca93bfdc2
    Error Number:207,State:1,Class:16
    

  • Sebastiaan Janssen

    If only we had a button for that ;-)

    enter image description here

    Anyway, make sure to check out my comment above!

  • Joseph

    32 posts

    146 karma points

    May 24, 2016 @ 16:58

    Joseph

    Ha, tried it but the editor only seemed to highlight the top line :)

    Thanks for the quick responses… Normally mid reply when they come in ;)

    Thinking you are right and it may be worth going straight to 7.4.3 and reporting back. Generally been in the mindset of upgrading to the nearest non-minor revision when having to jump a few versions… helps me understand the new bits introduced at each stage (such as new optional flexible LB in 7.3.0) and take any actions. Any minor revisions or a diff of only a few version increments then happy to just skip to latest, unfortunately just a little behind on the updates on this one so decided to do it incrementally…

    As you have shown, the updates seem to work on your end — so will see if the leap to 7.4.3 has any joy.

  • Joseph

    32 posts

    146 karma points

    May 24, 2016 @ 17:21

    Joseph

    Just updated to 7.4.3 from 7.3.1 and still have the same issue unfortunately… same errors.

    The trace logs show the application as starting up as 7.4.3 but no luck at the authorise stage again.

  • Joseph

    32 posts

    146 karma points

    May 24, 2016 @ 17:26

    Joseph

    Also worth noting that I have included the rewrite rule provided in one of the links provided for:

    <rule name="Exclude install folder from rewriting" stopProcessing="true">
                 <match url="install/(.*)$" />
                 <action type="None" />
            </rule>
    

  • Sebastiaan Janssen

    I don’t know what your rewrite rules look like but the error you posted points at that being the problem, just disable all the rewrite rules before you upgrading and try again!

    If you post the rewrites I can have a look. :)

  • Joseph

    32 posts

    146 karma points

    May 25, 2016 @ 09:17

    Joseph

    Hi Sebastiaan,

    Yep, correct… one of the rewrites was catching the request. The inclusion of that rule above was not enough on its own as one of the others took precedence.

    Currently reviewing the rules and looking at how they can be implemented or adjusted to correct this.

    Thanks for the assistance, much appreciated.

  • Jeroen Breuer

I wrote a script to add a column in a table and on successful execution update its values.
I know it’s just a simple script but what is wrong with the ‘IF NOT EXISTS’ statement why script between BEGIN and END is not executing and return error . I verified there is no Database level DDL trigger to stop adding column in database.

Msg 207, Level 16, State 1, Line 24
Invalid column name ColumnName.

DECLARE @CloumnAdded bit
SET @CloumnAdded = 0

IF NOT EXISTS ( SELECT  1
                FROM    Sys.Columns
                WHERE   [Object_ID] = Object_ID('DBName.dbo.TableName')
                        AND Name = 'ColumnName' ) 
    BEGIN

        ALTER TABLE TableName  ADD ColumnName varchar(120)

        SET @CloumnAdded = 1

        select @CloumnAdded, 'step 1 '
    END


IF ( @CloumnAdded = 1 ) 
    BEGIN
        select @CloumnAdded,'step 2'

        UPDATE  TableName
        SET     ColumnName = '2669'

        select @CloumnAdded,'step 3'
    END

GO

asked Jan 14, 2015 at 7:33

AA.SC's user avatar

0

Your prolem occurs because of the different steps involved in query execution. First comes parsing, then binding and finally execution. In parsing the submitted text is verified as valid SQL and converted to an internal representation. Binding resolves the names from the submitted SQL to objects inside SQL Server’s catalogue. Unfortuately TableName.ColumnName does not exist when binding is attempted so that part fails.

There are two things you can do*. First, split the query into two batches, one to create the column, one to update it. Only run the second if the first succeeds. Second, put the update in dynamic SQL and run it via exec sp_executesql. This effectively creates a second batch internally.

*That I can think of right now. I’m sure wiser heads could suggest others.

answered Jan 14, 2015 at 9:54

Michael Green's user avatar

Michael GreenMichael Green

24k13 gold badges50 silver badges94 bronze badges

1


  • December 6, 2011 at 12:35 pm

    #251607

    I just altered my table as follows:

    ALTER TABLE dbo.EpisodePackage

    ADD

    WebTagBroadViewId varchar(50) NULL

    , FormatSheetBroadViewId varchar(50) NULL

    , OnAirOfferBroadViewId varchar(50) NULL

    , FundingBedBroadViewId varchar(50) NULL

    then I alterd my Stored procedure:

    Update dbo.EpisodePackage

    Set WebTagBroadViewId = ‘1’

    where id = 586

    I get an error: on the line for:

    Set WebTagBroadViewId = ‘1’

    Msg 207, Level 16, State 1 Invalid column name ‘WebTagBroadViewId’.

    How can I resolve it?

  • Gail Shaw

    SSC Guru

    Points: 1004494

    Did you run the ALTER TABLE. Did it succeed?

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass

  • Johan Bijnens

    SSC Guru

    Points: 135009

    Did you commit the alter table statement ?

    What’s the @@opentran count for that session ?

  • Faye Fouladi

    SSCrazy

    Points: 2770

    The Alter Table statement succedded well.

    When I expand the table columns, I already see the added columns. Is there anything ellse I need to do for the stored procedure to see the cloumns?

  • toddasd

    SSCertifiable

    Points: 6298

    Faye Fouladi (12/6/2011)


    The Alter Table statement succedded well.

    When I expand the table columns, I already see the added columns. Is there anything ellse I need to do for the stored procedure to see the cloumns?

    There is nothing else you need to do. Check that you are not running the alter procedure statement on a different database. For example, run your code as one entire script:

    ALTER TABLE dbo.EpisodePackage

    ADD

    WebTagBroadViewId VARCHAR(50) NULL

    , FormatSheetBroadViewId VARCHAR(50) NULL

    , OnAirOfferBroadViewId VARCHAR(50) NULL

    , FundingBedBroadViewId VARCHAR(50) NULL

    GO

    ALTER PROCEDURE dbo.UpdatePackage

    AS

    UPDATE dbo.EpisodePackage

    SET WebTagBroadViewId = '1'

    WHERE id = 586

    GO

    ______________________________________________________________________________
    How I want a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.

  • Faye Fouladi

    SSCrazy

    Points: 2770

    I have something like this in the stored proc:

    — table variable for the BroadView data transformed into PackagingForms format

    DECLARE @BroadViewData TABLE

    (

    EpisodeId INT,

    EpisodePackageFormatId INT,

    EpisodePackageNumber VARCHAR(50),

    WebTagBroadViewId VARCHAR(50),

    FormatSheetBroadViewId VARCHAR(50),

    OnAirOfferBroadViewId VARCHAR(50),

    FundingBedBroadViewId VARCHAR(50),

    FlattenedInd CHAR(1),

    BroadViewId INT,

    BroadViewHashCode VARBINARY(MAX),

    RowId INT IDENTITY,

    UNIQUE CLUSTERED (BroadViewId, RowId)

    )

    The data for updating EpisodePackage table and updating those new fields is coming from this table variable. I also added the fields to the table variable. Do you think I should do something different becuase there is table variable involved here?

  • mhike2hale

    SSC Eights!

    Points: 858

    Is there trigger associated with this table?

    «Often speak with code not with word,
    A simple solution for a simple question»

  • toddasd

    SSCertifiable

    Points: 6298

    Faye Fouladi (12/6/2011)


    I have something like this in the stored proc:

    The data for updating EpisodePackage table and updating those new fields is coming from this table variable. I also added the fields to the table variable. Do you think I should do something different becuase there is table variable involved here?

    The only thing I can think of is maybe your table aliases are mixed up in the update statement. Post your whole proc.

    ______________________________________________________________________________
    How I want a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.

  • Erwin Dockx

    SSC Eights!

    Points: 842

    Faye Fouladi (12/6/2011)


    I have something like this in the stored proc

    Have you tried recompiling the stored procedure?

    exec sp_recompile 'your_proc_name_goes_here';

    exec sp_refreshsqlmodule 'your_proc_name_goes_here';

    _____________________________________________________
    Do not go past the mark you aimed for, but learn when to stop.

    You can find me on LinkedIn.
    I support The Programmer’s Bill of Rights.

    MCITP, MCDBA, MCSD

  • glothin

    SSC Rookie

    Points: 45

    One thing important to note: GO is not a SQL Server command, but a tool of SQL Management studio.

    When you run that script directly, SQL MS executes it batches separated by the ‘GO’. Therefore the new columns are committed/posted before update is ran.

    GO does not work in a stored procedure. When the procedure is compiled, it simply does not recognize the alter table.

    I have inherited a script with a similiar problem. I welcome a better solution than I have.

    My terrible temporary workaround is to create the table outside the stored procedure so that it contains all the columns it will eventually contain inside the stored procedure. Then the stored procedure will compile.

    If the table exists when the procedure is compiled it will work. Then my stored procedure will:

    1. drops the table if it exists;

    2. creates the new table with one field Junk(200)

    3. Perform bulk insert into my table

    4. alters my table and adds columns used to more precisely split up the data from the bulk insert

    5. Performs updates and other commands

    In my case using the #temp session tables improve the situation. The script can also be rewritten to extract data from the imported table to the correct columns or copy to a second table.

  • toddasd

    SSCertifiable

    Points: 6298

    As far as I can tell, the OP is not trying to alter a table within a proc. OP has run the alter table and is now trying to alter a proc which is returning the column not found error. We need to see the proc.

    ______________________________________________________________________________
    How I want a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.

  • Faye Fouladi

    SSCrazy

    Points: 2770

    No triggers associated with this stored procedure.

Viewing 12 posts — 1 through 11 (of 11 total)

Hi Guys,

I’m was create all table on database Sql Server version 9.00.3042.00(2020) and then I’m want make automatic model that generate from Entity Framework in Visual Studio 2019 via Package Manager Console but alwasy get this error

Invalid column name 'has_filter'.
Invalid column name 'filter_definition'.

 Below the error shown.

PM> Scaffold-DbContext "Server=DESKTOP-REM8S41SQLEXPRESS;Database=db_klinik;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Database -Context "ApplicationDbContext" -DataAnnotations
Build started...
Build succeeded.
To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
Security Warning: The negotiated TLS 1.0 is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later.
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'has_filter'.
Invalid column name 'filter_definition'.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerDatabaseModelFactory.GetIndexes(DbConnection connection, IReadOnlyList`1 tables, String tableFilter)
   at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerDatabaseModelFactory.GetTables(DbConnection connection, DatabaseModel databaseModel, Func`3 tableFilter, IReadOnlyDictionary`2 typeAliases)
   at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerDatabaseModelFactory.Create(DbConnection connection, DatabaseModelFactoryOptions options)
   at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerDatabaseModelFactory.Create(String connectionString, DatabaseModelFactoryOptions options)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions databaseOptions, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
   at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluralize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, String modelNamespace, String contextNamespace, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluarlize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:cdd89a38-9156-4634-b34d-ff0e4532ac4f
Error Number:207,State:1,Class:16
Invalid column name 'has_filter'.
Invalid column name 'filter_definition'.

Any help could be apriciate.

Понравилась статья? Поделить с друзьями:
  • Error number 18456 sql server
  • Error number 145
  • Error number 144
  • Error number 138 occurred
  • Error number 1205 lock wait timeout exceeded try restarting transaction