首页 > 解决方案 > ASP.NET 和实体框架中的网页给出了我正在努力解决的错误

问题描述

编辑:通过删除和重新创建实体数据库连接解决了这个问题

我正在创建一个网站,该网站将从表单中获取数据并将其存储在数据库中。我正在使用 C#、ASP.NET 和实体框架。我计划在本地服务器上托管这个网站,网站/服务器可能会重新启动,我需要代码不覆盖任何数据。我在 ASP.NET 和实体框架中的网页给出了我正在努力解决的错误。在我保存 db.SaveChanges(); 是错误到达的地方。

我曾经将我的 ID 设置为唯一标识符,它会通过,除非它不会创建新行。所以我将我的主键更改为 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

标签: c#asp.netsql-serverentity-framework

解决方案


因此,要回答有关 uniqueidentifier 字段的问题,您需要向要进入数据库的模型添加一个新的 guid。你可以用这样的东西来做到这一点,在你的using陈述之前添加:

model.ID = Guid.NewGuid();

确保在文件顶部也有导入“系统”库的语句,因为 Guid 对象是其中的一部分。

using System;

.NET 代码中的 Guid 只是一个 16 位的唯一标识符,因此它会与数据库中的 ID 字段完美结合。

关于数据库如何工作的一些明确性 - count() 函数不会在服务器重新启动时更改,唯一会更改的时间是数据本身是否被清除或更改。希望这不会是一个问题,但如果你不确定我会问你公司的某个人,他们可能知道数据清理是如何工作的/如果它曾经发生过,然后从那里开始。

在添加新的 ID 时,您不需要检查 ID 是否为空或空,如您列出的 - Guid 的重点是它将 100% 的时间是唯一的,因此通过添加该 model.ID正如我在上面显示的那样,您应该能够避免检查该字段。

干杯!


推荐阅读