РЕДАКТИРОВАТЬ: РЕШИЛИ, УДАЛЯЯ И УДАЛЯЯ СОЕДИНЕНИЕ С БД ENTITY
Я создаю веб-сайт, который будет принимать данные из формы и сохранять их в базе данных.Я использую C #, ASP.NET и Entity Framework.Я планирую разместить этот веб-сайт на локальном сервере, веб-сайт / сервер может быть перезапущен, и мне нужен код, чтобы не перезаписывать какие-либо данные.Моя веб-страница в ASP.NET и Entity Framework выдает ошибку, которую я пытаюсь устранить.на моем сохранении db.SaveChanges ();это то место, где появляется ошибка.
Раньше мой идентификатор устанавливался в качестве уникального идентификатора, и он проходил, за исключением того, что не создавал новые строки.Поэтому я изменил свой первичный ключ на ID, который является int.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core;
using System.Data.Entity.SqlServer;
using System.Data.Entity.Migrations;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.Spatial;
using System.Data.Entity.Utilities;
using System.Data.Entity.Validation;
namespace EngiData
{
public partial class WebForm2 : System.Web.UI.Page
{
EandIForm model = new EandIForm();
string idValue = "";
string productionValue = "";
string machineValue = "";
string nameValue = "";
string workOrderNumberValue = "";
string partNumberValue = "";
string prefixValue = "";
string programNumberValue = "";
string tFileValue = "";
string revisionValue = "";
string programmerValue = "";
string machineCollisionValue = "";
string probingValue = "";
string feedSpeedValue = "";
string spindleDirectionvalue = "";
string depthOfCutValue = "";
string toolClearancesValue = "";
string toolCallOutValue = "";
string machineWorkOffSetValue = "";
string programDoesntMeetPrintValue = "";
string coolantCommandValue = "";
string gmValue = "";
string partTransferValue = "";
string programImprovementValue = "";
string otherValue = "";
string details = "";
EandIEntities3 myDBEntities = new EandIEntities3();
SqlConnection con = new SqlConnection(@"Data Source=ste1sqlt01;Initial Catalog=EandI;Persist Security Info=True;User ID=*******;Password=*******");
//con.Open();
//SqlCommand cmd = con.CreateCommand();
//cmd.CommandType = System.Data.CommandType.Text;
//SqlConnection con = new SqlConnection(@"Data Source=ste1sqlt01;Initial Catalog=EandI;Persist Security Info=True;User ID=********;Password=*************");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void submitButton_Click(object sender, EventArgs e)
{
if (productLineDropDown.SelectedItem.Value == "0")
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Please select a product line" + "' );", true);
}
else
if (productLineDropDown.SelectedItem.Value == "Long Sweep")
{
productionValue = "Long Sweep";
}
else
if (productLineDropDown.SelectedItem.Value == "Fittings")
{
productionValue = "Fittings";
}
else
if (productLineDropDown.SelectedItem.Value == "Plug Valve")
{
productionValue = "Plug Valve";
}
else
if (productLineDropDown.SelectedItem.Value == "Pumps")
{
productionValue = "Pumps";
}
else
if (productLineDropDown.SelectedItem.Value == "Union Connector")
{
productionValue = "Union Connector";
}
else
if (productLineDropDown.SelectedItem.Value == "Wellhead")
{
productionValue = "Wellhead";
}
else
if (productLineDropDown.SelectedItem.Value == "Well Service Pumps")
{
productionValue = "Well Service Pumps";
}
if (machineListDropDown.SelectedItem.Value == "0")
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Please select a machine." + "' );", true);
}
else
{
model.Machine = machineListDropDown.SelectedItem.Value;
}
if (nameTextbox0.Text != "")
{
nameValue = nameTextbox0.Text;
model.Submitter = nameValue.Trim();
}
if (workOrderTextbox0.Text != "")
{
workOrderNumberValue = workOrderTextbox0.Text;
model.Work_Order_Number = workOrderNumberValue.Trim();
}
model.Production_Line = productionValue.Trim();
//model.ID = Guid.NewGuid();
model.Part_Number = partNumberValue.Trim();
model.Program_Prefix = prefixValue.Trim();
model.Program_Number = programNumberValue.Trim();
model.TFile = tFileValue.Trim();
model.Revision = revisionValue.Trim();
model.Programmer = programmerValue.Trim();
model.Machine_Collision = machineCollisionValue.Trim();
model.Probing = probingValue.Trim();
model.Feed_Speed = feedSpeedValue.Trim();
model.Spindle_Direction = spindleDirectionvalue.Trim();
model.Depth_of_Cut = depthOfCutValue.Trim();
model.Tool_Clearance = toolClearancesValue.Trim();
model.Tool_Call_Outs = toolCallOutValue.Trim();
model.Machine_WorkOffSet = machineWorkOffSetValue.Trim();
model.Program_Doesnt_Match = programDoesntMeetPrintValue.Trim();
model.Coolant_Commands = coolantCommandValue.Trim();
model.GM_Code = gmValue.Trim();
model.Part_Transfer = partTransferValue.Trim();
model.Program_Improvement = programImprovementValue.Trim();
model.Other = otherValue.Trim();
model.Details = details.Trim();
using (EandIEntities3 db = new EandIEntities3())
{
db.EandIForms.Add(model);
db.SaveChanges();
}
productionValue = "";
machineValue = "";
nameValue = "";
workOrderNumberValue = "";
partNumberValue = "";
prefixValue = "";
programNumberValue = "";
tFileValue = "";
revisionValue = "";
programmerValue = "";
machineCollisionValue = "";
probingValue = "";
feedSpeedValue = "";
spindleDirectionvalue = "";
depthOfCutValue = "";
toolClearancesValue = "";
toolCallOutValue = "";
machineWorkOffSetValue = "";
programDoesntMeetPrintValue = "";
coolantCommandValue = "";
gmValue = "";
partTransferValue = "";
programImprovementValue = "";
otherValue = "";
details = "";
Response.Redirect("Submitted.aspx");
}
protected void clearButton_Click(object sender, EventArgs e)
{
}
}
}
Это ошибка, которую я получаю на мою
db.SaveChanges();
System.Data.Entity.Infrastructure.DbUpdateException was unhandled by user code
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at EngiData.WebForm2.submitButton_Click(Object sender, EventArgs e) in C:\Users\hatchb.TP\Documents\Visual Studio 2015\Projects\EngiData\EngiData\WebForm2.aspx.cs:line 191
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException:
Class=16
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=1
Message=Operand type clash: uniqueidentifier is incompatible with int
Number=206
Procedure=""
Server=ste1sqlt01
Source=.Net SqlClient Data Provider
State=2
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.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, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
InnerException:
В моей базе данных все мои поля - varchar (50), кроме ID, который представляет собой INT с идентификационной спецификацией.,
У меня есть несколько фрагментов кода, которые я закомментировал, пытаясь сделать это несколькими различными способами.Кто-нибудь может увидеть, где проблема в моем коде?
моя база данных называется EandIForm
мое соединение с платформой сущностей называется EandIEntities3