我有一个_job对象,这个_job对象有相关的工作。当我删除相关的工作时,我收到了这个错误:
{“存储更新,插入或删除语句影响了意外情况 行数(0)。自那以后,实体可能已被修改或删除 实体已加载。看到 http://go.microsoft.com/fwlink/?LinkId=472540了解有关的信息 理解和处理乐观并发异常。“}
这是我的代码:
if (_job.relatedJobs.Any())
{
foreach(var relatedJob in _job.relatedJobs.ToList())
{
jobList.Add(relatedJob );
_job.relatedJobs.Remove(relatedJob);
}
_db.Entry(_job).State = EntityState.Modified;
}
_db.Jobs.Add(_job);
_db.SaveChanges(); //I'm getting the exception at this line
我该如何解决这个问题?感谢。
答案 0 :(得分:0)
这很有效。
以下是创建数据库表的方法,使用您的数据库而不是我的breaz数据库名称:
USE [Breaz]
GO
/****** Object: Table [dbo].[Job] Script Date: 1/12/2017 10:00:24 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Job](
[Id] [int] IDENTITY(1,1) NOT NULL,
[JobDescription] [varchar](50) NULL,
CONSTRAINT [PK_Job] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[JobRelated] Script Date: 1/12/2017 10:00:24 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[JobRelated](
[Id] [int] IDENTITY(1,1) NOT NULL,
[JobId] [int] NULL,
[RelatedJobDescription] [varchar](10) NULL,
CONSTRAINT [PK_JobRelated] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Job] ON
GO
INSERT [dbo].[Job] ([Id], [JobDescription]) VALUES (1, N'Cleaning')
GO
SET IDENTITY_INSERT [dbo].[Job] OFF
GO
SET IDENTITY_INSERT [dbo].[JobRelated] ON
GO
INSERT [dbo].[JobRelated] ([Id], [JobId], [RelatedJobDescription]) VALUES (3, 1, N'Mopping')
GO
INSERT [dbo].[JobRelated] ([Id], [JobId], [RelatedJobDescription]) VALUES (4, 1, N'Sweeping')
GO
SET IDENTITY_INSERT [dbo].[JobRelated] OFF
GO
ALTER TABLE [dbo].[JobRelated] WITH CHECK ADD CONSTRAINT [FK_JobRelated_Job] FOREIGN KEY([JobId])
REFERENCES [dbo].[Job] ([Id])
GO
ALTER TABLE [dbo].[JobRelated] CHECK CONSTRAINT [FK_JobRelated_Job]
GO
为这两个表创建一个ADO.NET实体数据模型(EDMX)
这是你的控制器:
public ActionResult Index12() //this Method name can change
{
using (BreazEntities2 e = new BreazEntities2()) //you will use the dbcontext name you have
{
try
{
var _job = e.Jobs.Find(1);
if (_job.JobRelateds.Any())
{
foreach (var relatedJob in _job.JobRelateds.ToList())
{
Job addToJob = new Job();
//no relateds for this
addToJob.JobDescription = "From related to Job->" + relatedJob.RelatedJobDescription;
e.Jobs.Add(addToJob);
e.JobRelateds.Remove(relatedJob);
}
}
e.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var failure in ex.EntityValidationErrors)
{
string validationErrors = "";
foreach (var error in failure.ValidationErrors)
{
validationErrors += error.PropertyName + " " + error.ErrorMessage;
}
}
}
}
return View();
}