简体   繁体   English

EF继续抛出错误System.InvalidOperationException ASP.NET MVC

[英]EF keep throwing error System.InvalidOperationException ASP.NET MVC

I need to insert parent record through for loop and based on newly generate ID need to create child records, but EF doesn't seem to be working well. 我需要通过for循环插入父记录,并且基于新生成的ID需要创建子记录,但是EF似乎运行不佳。

Based on answers suggested in different stackoverflow questions, I call db.savechanges() after all foreach loop but it's just creating two records whereas foreach loop contains 6 items. 根据不同的stackoverflow问题中建议的答案,我在所有foreach循环之后都调用db.savechanges() ,但它只是创建两个记录,而foreach循环包含6个项目。

Exception: 例外:

System.InvalidOperationException: 'The changes to the database were committed successfully, but an error occurred while updating the object context. System.InvalidOperationException:'已成功提交对数据库的更改,但是在更新对象上下文时发生错误。 The ObjectContext might be in an inconsistent state. ObjectContext可能处于不一致状态。 Inner exception message: A referential integrity constraint violation occurred: The property value(s) of 'new_job.job_id' on one end of a relationship do not match the property value(s) of 'job_address_point.job_id' on the other end.' 内部异常消息:违反了参照完整性约束:关系一端的'new_job.job_id'的属性值与另一端的'job_address_point.job_id'的属性值不匹配。

InvalidOperationException: A referential integrity constraint violation occurred: The property value(s) of 'new_job.job_id' on one end of a relationship do not match the property value(s) of 'job_address_point.job_id' on the other end. InvalidOperationException:发生了引用完整性约束冲突:关系一端的'new_job.job_id'的属性值与另一端的'job_address_point.job_id'的属性值不匹配。

Code: 码:

foreach (var cartype in cartypes)
{
    if (cartype.TotalCar != 0)
    {
        for (int i = 0; i < cartype.TotalCar; i++)
        {
            //new_job job = new new_job();
            //new_job_db object same as new_job where I'm assigning all values to properties 
            //received in parameter

            new_job job = new_job_db.CloneJson();

            job.job_ref = str + createRandomNumber();
            job.car_type_id = cartype.CarTypeId;
            db.new_job.Add(job);
            db.SaveChanges();
            var jobId = job.job_id;
            var jobDate = job.job_date;
            //multi address
            foreach (SelectedPoint p in _newjobdto.addresses)
            {
                job_address_point addr = new job_address_point();
                addr.job_id = jobId;
                addr.passenger_id = passengerId;
                addr.job_date = jobDate;
                addr.point_seq = Convert.ToInt32(p.PointSeq);
                addr.place_id = p.PlaceId;
                addr.formatted_address = p.FormattedAddress;
                addr.lat = p.Lat;
                addr.lng = p.Lng;
                addr.post_code = p.PostCode;
                addr.zone_name = p.ZoneName;
                addr.mile = p.Miles;
                addr.km = p.Kms;
                addr.charges = p.Charges;
                db.job_address_point.Add(addr);    
            }
            db.SaveChanges();
        }
    }
}

Update: 更新:

Here are debug result: on 1st round it generate the Id and on 2nd round it throwing the exception: 以下是调试结果:在第1轮它会生成ID,在第2轮它会抛出异常:

1st round: 第一轮: 在此处输入图片说明

2nd round: 第二轮: 在此处输入图片说明

cartypes: cartypes: 在此处输入图片说明

Update: 更新:

As comment to Gabriel Luci answer, I implemented CloneJson() extension method from this question but its giving same error. 作为对Gabriel Luci答案的评论,我从该问题实现了CloneJson()扩展方法,但给出了相同的错误。 I want to take the processing of 20 properties outside of foreach loop and copy it into newly create object inside the foreach loop where there only two properties need to set. 我要处理foreach循环外的20个属性,并将其复制到foreach循环内的新创建的对象中,这里仅需要设置两个属性。

First: 第一:

new_job job = new new_job();
//new_job_db object same as new_job where I'm assigning all values to properties 
//received in parameter
job = new_job_db;

There are a couple questionable things about this: 关于此有两点可疑的事情:

  1. The second line is overwriting the first. 第二行覆盖第一行。 Either set it to new new_job() , or set it to new_job_db , not both. 要么将其设置为new new_job() ,要么将其设置为new_job_db ,但不能两者都设置。
  2. What is new_job_db ? 什么是new_job_db If it's a record that has already been saved to the database, it's possible this is the reason for the exception, but I can't say without seeing how this is declared. 如果记录已经保存到数据库中,则可能是导致异常的原因,但是我不能不说如何声明而说。

Next: 下一个:

db.Entry(job).State = System.Data.Entity.EntityState.Added;
db.new_job.Add(job);

Don't set the State . 不要设置State You don't need to. 不用了 Adding it to the db.new_job collection will do that for you. 将其添加到db.new_job集合将为您完成此操作。 This could also be what's causing the exception. 这也可能是导致异常的原因。

暂无
暂无

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

相关问题 ASP.Net 错误 System.InvalidOperationException - ASP.Net error System.InvalidOperationException System.InvalidOperationException:无法在数据迁移中的asp.net mvc 6上解析EF7中的项目“ ef” - System.InvalidOperationException: Unable to resolve project 'ef' in EF7 at asp.net mvc 6 in data migration 错误:ASP.NET WebAPI中的System.InvalidOperationException - Error: System.InvalidOperationException in ASP.NET WebAPI System.InvalidOperationException:无法解析 ASP.NET Core 中的服务 - System.InvalidOperationException: Unable to resolve service in ASP.NET Core ASP.NET 核心 API System.InvalidOperationException 在本地化 - ASP.NET Core API System.InvalidOperationException in localization ASP.NET 核心错误:System.InvalidOperationException:尝试激活时无法解析服务类型 - ASP.NET Core error: System.InvalidOperationException: Unable to resolve service for type while attempting to activate EF和Web服务错误“ System.InvalidOperationException” - EF and Webservice Error “System.InvalidOperationException” ASP.NET 错误:内部服务器错误:System.InvalidOperationException:尝试激活时无法解析服务类型 - ASP.NET Error: Internal Server Error: System.InvalidOperationException: Unable to resolve service for type while attempting to activate MVC 5中带有EF 6的错误“ System.InvalidOperationException:IEntityChangeTracker的多个实例无法引用一个实体对象。” - Error in MVC 5 with EF 6 “ System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.” WCF和EF中的System.InvalidOperationException - System.InvalidOperationException in WCF and EF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM