Dynamic SQL Query - asp.net

I'm trying to retrieve information based on Year, Faculty, Quarter, and Course. Depending on how specific the user would like to be (Faculty for the year, quarter, course, etc...).
string a = "";
if (DDLYear.SelectedValue == "Select")
{
return;
}
else
{
a = DDLYear.SelectedValue;
}
if (DDLFaculty.SelectedValue != "Select")
{
arrFields.Add("Employee.Employee_ID = " + DDLFaculty.SelectedValue);
}
if (DDLQuarter.SelectedValue != "Select")
{
arrFields.Add("Quarter.Quarter_Name = " + DDLQuarter.SelectedValue);
}
if (DDLCourse.SelectedValue != "Select")
{
arrFields.Add("Course.Title = " + DDLCourse.SelectedValue);
}
Custom.SelectCommand = Custom.SelectCommand =
"SELECT AVG(Rating.Score) AS YearsAverageScore
FROM Rating INNER JOIN Survey ON Rating.Survey_ID = Survey.Survey_ID
INNER JOIN Course_Quarter ON Survey.CourseQuarter_ID = Course_Quarter.CourseQuarter_ID
INNER JOIN Quarter ON Course_Quarter.Quarter_ID = Quarter.Quarter_ID
INNER JOIN Employee ON Course_Quarter.Employee_ID = Employee.Employee_ID
WHERE (Quarter.Year = " + a + String.Join("and ", arrFields.ToArray()) + ")";
When I try to retrieve information for Year 2000 on Employee 'A' I run into an error: "Incorrect syntax near 'mployee'". There is no 'mployee' in the code except for that in Employee. When I add a space between " Employee" I run into the same error except it says: Incorrect syntax near 'Employee'"
The Error Report:
Incorrect syntax near 'Employee'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'Employee'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near 'Employee'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +2073502
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5064460
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
System.Data.SqlClient.SqlDataReader.get_MetaData() +86
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +311
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +987
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +144
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +319
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable) +92
System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1618
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +21
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +143
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +74
System.Web.UI.WebControls.GridView.DataBind() +4
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +66
System.Web.UI.WebControls.GridView.OnPreRender(EventArgs e) +26
System.Web.UI.Control.PreRenderRecursiveInternal() +103
System.Web.UI.Control.PreRenderRecursiveInternal() +175
System.Web.UI.Control.PreRenderRecursiveInternal() +175
System.Web.UI.Control.PreRenderRecursiveInternal() +175
System.Web.UI.Control.PreRenderRecursiveInternal() +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2496

You should give us the SQL after the substitution, but your problem is probably among these:
You're getting "Quarter.Year = aand. . ." because of there's a space missing after "a"
The values you're comparing to what I'm guessing are string fields (QuarterName, Course Title) don't have quotation marks around them
String.Join probably does not stick "and" at the very beginning of the string.

When you use equality on a string in SQL you need to wrap it around quotes. Usually '. If the column type is numeric (ie long, int etc) then you do not need the quotes.
You can also use the String.Format which will improve readability. An example of this is:
String.Format("Quarter.Quarter_Name = '{0}'", DDLQuarter.SelectedValue.ToString());
Here is your original code with string equality fixed:
if (DDLFaculty.SelectedValue != "Select")
{
arrFields.Add("Employee.Employee_ID = '" + DDLFaculty.SelectedValue + "'");
}
if (DDLQuarter.SelectedValue != "Select")
{
arrFields.Add("Quarter.Quarter_Name = '" + DDLQuarter.SelectedValue + "'");
}
if (DDLCourse.SelectedValue != "Select")
{
arrFields.Add("Course.Title = '" + DDLCourse.SelectedValue + "'");
}

Related

Server Error in '/' Application. Incorrect syntax near ')'

I am trying to make this work for an assignment, and I can't seem to figure out what's wrong. I am making a web application in Visual Studio 2012. I get this error when I try to post the form to the database. I am a total noob and this is the first time I have ever posted here so please bear with me. I've checked spelling on column names and everything seems to be in order.
Server Error in '/genericname' Application.
Incorrect syntax near ')'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ')'.
Source Error:
Line 18: myCom.Parameters.AddWithValue("#fullText", txtFullText.Text)
Line 19: myCon.Open()
Line 20: myCom.ExecuteNonQuery()
Line 21: myCon.Close()
Line 22:
Source File: F:\Documents\School\WebAppDevelopment\Assignment1\****\admin\add-article.aspx.vb Line: 20
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near ')'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1754082
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5295874
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +269
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1325
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +205
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +160
admin_add_article.btnSave_Click(Object sender, EventArgs e) in F:\Documents\School\WebAppDevelopment\Assignment1\CarlsonDavidLab2\admin\add-article.aspx.vb:20
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9634378
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
Here is my code:
Any help is appreciated. Thanks!
You have an extra , after the subDate in this line:
mySQL &= "summary, fullText, subDate,) VALUES (#headline, #postDate, #author, #category, "
Additional note, instead of using AddWithValue, you should use Parameters.Add and specify the underlying database datatype.
More on this here.

System.Data.SqlClient.SqlException: '' is not a recognized built-in function name

Here is the error I am getting:
Server Error in '/pi' Application.
'Dexsys' is not a recognized built-in function name.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: 'Dexsys' is not a recognized built-in function name.
Source Error:
Line 108: Dim dsTop1 As New DataSet
Line 109: Dim daTop1 As New SqlDataAdapter(strSQL3, cnIT3)
Line 110: daTop1.Fill(dsTop1)
Line 111: cnIT3.Close()
Line 112:
Source File: C:\inetpub\wwwroot\pi\admin\rptSummary.aspx.vb Line: 110
Stack Trace:
[SqlException (0x80131904): 'Dexsys' is not a recognized built-in function name.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1789294
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5340642
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +61
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +377
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1421
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +137
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +140
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +316
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +88
admin_history.getTimes() in C:\inetpub\wwwroot\pi\admin\history.aspx.vb:109
admin_history.Page_Load(Object sender, EventArgs e) in C:\inetpub\wwwroot\pi\admin\history.aspx.vb:217
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212
Here is the function causing the probelm:
Private Sub getTimes()
Dim strSQL3 As String = "select datetimestamp, cast(datepart(yyyy, datetimestamp) as varchar(4)) + '-' + cast(datepart(mm, datetimestamp) as varchar(2)) + '-' + cast(datepart(dd, datetimestamp) as varchar(2)) as yyyyddmm, datepart(hh,datetimestamp) * 3600 + datepart(mm,datetimestamp) * 60 as protime, datepart(hh,datetimestamp) * 3600 + datepart(mm,datetimestamp) + 18000 as protimeplus5 from dex_racklabels.dbo.inv_master where recid = " & Session("INVID")
Dim cnIT3 As New SqlConnection
cnIT3.ConnectionString = ConfigurationManager.ConnectionStrings("csracklabels").ConnectionString
cnIT3.Open()
Dim dsTop1 As New DataSet
Dim daTop1 As New SqlDataAdapter(strSQL3, cnIT3)
daTop1.Fill(dsTop1)
cnIT3.Close()
If dsTop1.Tables(0).Rows.Count > 0 Then
Session("intTm1") = dsTop1.Tables(0).Rows(0).Item("protime")
Session("inttm2") = dsTop1.Tables(0).Rows(0).Item("protimeplus5")
Session("yyyyddmm") = dsTop1.Tables(0).Rows(0).Item("yyyyddmm")
Session("datetimestamp") = dsTop1.Tables(0).Rows(0).Item("datetimestamp")
End If
End Sub
So I have tried to google this issue, and it always seems to be that we are passing something stupid over to SQL that is not recognized as a function.... But how am I getting 'Dexsys' when I don't have anything like that in this function?
Also when I cut out that strSQL3 and put it into SQL and run it.. it runs fine... Could it be the where at the end? How can I stop the code and display the value in the variable: Session("INVID")... I am used to just being able to do response.write(Session("INVID")) and then a response.end()...
I have come accross this issue a couple of times, and would really like to understand how to correct it and why it is happening. Thank you.
Figured it out...
1) I can use response.write and response.end lol... Stupid of me for not actually trying that...
2) Dexsys (2015-9-16) was what was in the Session Varaible... hence the error of the built in function!
Hmm i guess that your problem is with you Session("INVID") you could use the debug mode to check the variable name in the Visual Studio or show it in the Debug Session Like
Debug.Writeline(strSQL3)
'or
Console.WriteLine(strSQL3)
You could also wrap the function in Try Catch Exception so you could check better the error that is happenning. You could also get the specific version of the Exception to find more info.
Like this
Try
'your code goes here.
Catch ex As SqlException
throw
End Try

Update to EntityFramework 6 model isn't being reflected when WebAPI Controller is executed

I have added a database view to SQL Server 2012. After this I updated my EntityFramework (v6) model, built and validated it. From the ASP.Net WebAPI (v2) project I removed and added the reference my EntityFramework library to ensure I was referencing this most recent update. The controller has all the correct links to the context and the EF model classes. No errors in referencing the updates I made from this GET method:
public IEnumerable<RTV_DedicationComments> Get(int EntryNum)
{
//var query = from c in context.RTV_GetAllDedicationsNames orderby c.DedicationName where c.DedicationName.StartsWith(Name) select c;
var query = context.RTV_DedicationComments
.Where(d => d.EntryNumber == EntryNum)
.OrderBy(d => d.EntryNumber)
.Select(d => d);
var results = query.ToList();
return results;
}
At runtime the following error is returned on the innerexception:
{"Invalid column name 'PlatEntryNumber'.\r\nCould not use view or function 'dbo.RTV_DedicationComments' because of binding errors."} when the query is executed:
var results = query.ToList();
'PlatEntryNumber' was from the database and EF model prior to the update ut it has been removed and it doesn't show as a field from dbcontext in the controller.
I turned on the SQL Server profiler to see if the query was executing there and it did:
exec sp_executesql N'SELECT
[Project1].[EntryNumber] AS [EntryNumber],
[Project1].[CommentDate] AS [CommentDate],
[Project1].[Comment] AS [Comment],
[Project1].[CommentBy] AS [CommentBy]
FROM ( SELECT
[Extent1].[EntryNumber] AS [EntryNumber],
[Extent1].[CommentDate] AS [CommentDate],
[Extent1].[Comment] AS [Comment],
[Extent1].[CommentBy] AS [CommentBy]
FROM (SELECT
[RTV_DedicationComments].[EntryNumber] AS [EntryNumber],
[RTV_DedicationComments].[CommentDate] AS [CommentDate],
[RTV_DedicationComments].[Comment] AS [Comment],
[RTV_DedicationComments].[CommentBy] AS [CommentBy]
FROM [dbo].[RTV_DedicationComments] AS [RTV_DedicationComments]) AS [Extent1]
WHERE ([Extent1].[EntryNumber] = #p__linq__0) AND (#p__linq__0 IS NOT NULL)
) AS [Project1]
ORDER BY [Project1].[EntryNumber] ASC',N'#p__linq__0 int',#p__linq__0=5943651
What else can I check to remove the remnants of these database object references between the WebAPI and the EF?
Here is the entire stack trace:
System.Data.Entity.Core.EntityCommandExecutionException was unhandled by user code
HResult=-2146232004
Message=An error occurred while executing the command definition. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at RecWebAPI.Controllers.RTV_GetDedicationCommentsController.Get(Int32 PlatEntryNum) in e:\Development Test\RecTaxWebSLN3\RecWebAPI3\Controllers\RTV_GetDedicationCommentsController.cs:line 43
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Invalid column name 'PlatEntryNumber'.
Could not use view or function 'dbo.RTV_DedicationComments' because of binding errors.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=3
Number=207
Procedure=RTV_DedicationComments
Server=mysqlserver
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.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)
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 System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
InnerException:
The problem was with my WebAPI web.config file. The had a tag pointing to the old database. This is somewhat confusing to me because I thought the EF handled all the connections to the database and therefore no need for the WebAPI to have the database info. It is working now.

ASP.net, how to make my dropdownlist

I have a dropdownlist on my ASP.net page. It contains the primary key values from another table. It is using these values to put into a new, intersection table.
My problem is that, for readability/usability, displaying the primary keys themselves is not ideal. I would prefer to display the corresponding name field, but insert the primary key all the same. I have tried changing the datatextfield and leaving the value field as the pk and selecting either or both columns, but when I try to input it comes back as saying that a null value cannot be accepted.
Can anyone help please?
<InsertItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource4" DataTextField="BoatID" DataValueField="BoatID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:Rowing ClubConnectionString %>" SelectCommand="SELECT [BoatID] FROM [Boat]"></asp:SqlDataSource>
</InsertItemTemplate>
Thank you!
The following is the error page that comes up when trying to add to the table when the datatextfield has been changed to boat name and the sql includes the boat name column:
Server Error in '/' Application.
Cannot insert the value NULL into column 'BoatID', table 'Rowing Club.dbo.SessionBoats'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'BoatID', table 'Rowing Club.dbo.SessionBoats'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): Cannot insert the value NULL into column 'BoatID', table 'Rowing Club.dbo.SessionBoats'; column does not allow nulls. INSERT fails.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +1767866
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5352418
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +269
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1406
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +205
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +160
System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation) +380
System.Web.UI.WebControls.SqlDataSourceView.ExecuteInsert(IDictionary values) +399
System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback) +81
System.Web.UI.WebControls.DetailsView.HandleInsert(String commandArg, Boolean causesValidation) +365
System.Web.UI.WebControls.DetailsView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +584
System.Web.UI.WebControls.DetailsView.OnBubbleEvent(Object source, EventArgs e) +89
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.DetailsViewRow.OnBubbleEvent(Object source, EventArgs e) +80
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +121
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +156
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9528682
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

ASP.NET ListView with DataPager throwing error after going to next page

I have a problem in ListView with DataPager.
I have SqlDataSource
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ADSConnectionString %>"
SelectCommand="usp_posts_getall" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
and it was binded in ListView. I set my PageSize in DataPager to 5, so after navigating to next page.
It thrown an error
Procedure or function usp_posts_getall has too many arguments specified
in my usp_posts_getall, I only have 1 parameter
#thisCategoryID int
What went wrong?
[SqlException (0x80131904): Procedure or function usp_posts_getall has too many arguments specified.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1951450
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4849003
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2394
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
System.Data.SqlClient.SqlDataReader.get_MetaData() +83
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +954
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +130
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +287
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable) +92
System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1297
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +19
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +142
System.Web.UI.WebControls.ListView.PerformSelect() +57
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +73
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82
System.Web.UI.WebControls.BaseDataBoundControl.OnPreRender(EventArgs e) +22
System.Web.UI.Control.PreRenderRecursiveInternal() +80
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
ok sorry,
I forgot to clear the SelectParameters because in my Page_Load, I have this code:
Parameter param = new Parameter();
param.Name = "thisCategoryID";
param.Type = TypeCode.Int32;
param.DefaultValue = SelectedCategoryID.ToString();
SqlDataSource1.SelectParameters.Clear(); // <<--- and I forgot this
SqlDataSource1.SelectParameters.Add(param);
it's working now

Resources