简体   繁体   English

如何解决空数据库表上的乐观并发异常错误

[英]How to resolve optimistic concurrency exceptions error on empty DB table

Using ASP.NET MVC, Entity Framework to perform CRUD ops on a SQL Server database.使用 ASP.NET MVC,实体框架在 SQL 服务器数据库上执行 CRUD 操作。 I am inserting new information into the connected tables.我正在将新信息插入连接的表中。 I have numerous tables I do this operation on, but I've never come across this error before.我有很多表要执行此操作,但我以前从未遇到过此错误。

When I submit my data to the controller I it traverses through the typical EFF stuff.当我将数据提交到 controller 时,它会遍历典型的 EFF 内容。 However, when it hits my db.SaveChanges() line, I get this optimistic concurrency exceptions error, referencing that the data may have changed from the db.但是,当它到达我的db.SaveChanges()行时,我收到了这个乐观并发异常错误,指的是数据可能已经从数据库中更改。 In this particular situation there is no data in the table, so it doesn't make sense to me.在这种特殊情况下,表中没有数据,所以对我来说没有意义。

I followed the recommendation and read some about it.我遵循了建议并阅读了一些相关信息。 Implemented one of their fixes, but it doesn't work.实施了他们的修复之一,但它不起作用。 Doesn't work because it's seeking GetDatabaseValues() and there are none.不起作用,因为它正在寻找GetDatabaseValues()并且没有。 Have I missed something silly here?我在这里错过了什么愚蠢的事情吗? I'm simply taking form values and inserting them into two different tables I've set up.我只是获取表单值并将它们插入到我设置的两个不同的表中。

Here's the controller:这是 controller:

[HttpPost]
public ActionResult SubmitUwSelections(FormCollection form)
{
        var cbRating = form["cabRating"]; // Cab Raing ddl
        var filing = form["fileRqd"]; // filing required ddl
        var ifta = form["cbIfta"]; // IFTA cb
        var lossControl = form["lcRqd"]; // Loss control cb
        var app1 = form["AppInFile"]; //Application app in file cb
        var app2 = form["AppRqd"]; //Application app rqd cb
        var um1 = form["UMInFile"]; //UM in file cb
        var um2 = form["UMRqd"]; // UM rqd cb
        var terror1 = form["terrorInFile"]; // terror in file cb
        var terror2 = form["terrorRqd"]; // terror rqd cb
        var lossRun1 = form["LossRunInFile"];// loss run in file cb
        var lossRun2 = form["LossRunRqd"]; //Loss run rqd cb
        var inspect1 = form["cbVehicleInspectInFile"]; //vehicle inspect in file cb
        var inspect2 = form["cbVehicleInspectRqd"]; // vehicle inspect rqd cb
        var mvr1 = form["cbMvrInFile"]; // mvr in file cb
        var mvr2 = form["cbMvrRqd"]; // mvr rqd cb
        var psComments = form["cifComments"]; //section 2 comment box
        var uniqPolicy = form["UniqPolicy"];
        string c = uniqPolicy.ToString();
        int u = Convert.ToInt32(c);

        // need to form up and create variables for the segmentation part of the insert. 
        // Segmentation pieces. 
        var segYear = form["segYear"]; //seg tab segmentation year
        var tractors = form["tractors"]; //seg tab tractors
        var truck = form["trucks"]; //seg tab trucks
        var su = form["serviceUnits"]; //seg tab service units
        var estMileage = form["estAnnMile"]; // segmentation tab Est-Annual Mileage
        var estRvenue = form["estAnnRev"]; //seg tab est annual revenue
        var radius = form["radius"]; // seg tab radius ddl
        var primaryOp = form["primaryOperation"]; //Seg tab primary operation ddl

        int l, m, n, o, p = 0;
        l = Convert.ToInt32(segYear); //Converts seg year into int
        m = Convert.ToInt32(tractors); //converts seg tractors to int
        n = Convert.ToInt32(truck); //converts seg trucks to int
        o = Convert.ToInt32(su); //converts seg service units to int
        p = Convert.ToInt32(estMileage); //converts seg est ann mileage to int
        decimal revenue = Convert.ToDecimal(estRvenue); //converts seg est revenue to decimal

        using (TruckingDb db  = new TruckingDb())
        {
            // Create dto to insert Form collection items 
            CIF_Record_InsertDTO dto = db.CIF_Record.Find(u); //checking to see if row exists
            CIF_Record_InsertDTO dtoSend = new CIF_Record_InsertDTO();
            CIF_Segmentation_InsertDTO segDto = new CIF_Segmentation_InsertDTO();

            if (dto == null)
            {
                // create UniqPolicy dto
                dtoSend.UniqPolicyId = u;

                // Create user insert dto. 
                string user = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1);
                dtoSend.Underwriter = user;

                // set the cif record comments section. 
                dtoSend.Comments = psComments;

                // Set the UwSegmentation value
                dtoSend.UwSegmentationSubmit = true;

                // Set segmentation dto's
                segDto.SegmentationYear = l;
                segDto.Tractors = m;
                segDto.Trucks = n;
                segDto.ServiceUnits = o;
                segDto.EstAnnualMileage = p;
                segDto.EstAnnualRevenue = revenue;
                segDto.Radius = radius;
                segDto.PrimaryOperation = primaryOp;

                // 1. inserting dto's into two different tables
                db.CIF_Record.Add(dtoSend);  
                db.CIF_Segmentation.Add(segDto); //2.
            }
            else
            {
                // temporarily empty
            }

            bool saveFailed;

            do
            {
                saveFailed = false;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    saveFailed = true;

                    //update original values from the db
                    var entry = ex.Entries.Single();
                    entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                }
            } while (saveFailed);
        }

        return RedirectToAction("CompleteCIF");
}    

The do while just above what their first fix, but it doesn't work. do while的只是高于他们的第一个修复,但它不起作用。 Hits the catch and hits the entry.GetDatabaseValues() , but of course there's no OG values to begin with.击中并击中entry.GetDatabaseValues() ,但当然没有 OG 值开始。 Why is the saveChanges() not working?为什么saveChanges()不起作用? Thanks again for the help.再次感谢您的帮助。

Check that any columns that have automatically generated values in the database are marked in your entity configuration as Identity for key columns, and Computed for everything else.检查数据库中自动生成值的所有列是否在您的实体配置中标记为键列的Identity ,以及其他所有内容的Computed DateTime values may have issues with the SQL type and milliseconds, so check that they are DateTime2(7) may help. DateTime 值可能与 SQL 类型和毫秒有关,因此检查它们是否为 DateTime2(7) 可能会有所帮助。 Depending on the table structure, an insert can result in an Insert+Update and this could trigger the concurrency exception, which should only occur in Updates or Deletes, not Inserts.根据表结构,插入可能会导致插入+更新,这可能会触发并发异常,该异常只应发生在更新或删除中,而不是插入中。 When EF encounters a defaulted column it may confuse that as a concurrent update if it's not configured to account for that.当 EF 遇到默认列时,如果未将其配置为考虑这一点,它可能会将其混淆为并发更新。

See ( DbUpdateConcurrencyException on insert ) for details on DateTime related insert issues.有关 DateTime 相关插入问题的详细信息,请参阅( 插入 DbUpdateConcurrencyException )。 In their case, ensuring they were set to "None" for DB Generated options was needed.在他们的情况下,需要确保将 DB Generated 选项设置为“None”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM