无法从MVC中存在外键的表中删除行 [英] Unable to remove the row from table in which foreign key exists in MVC

查看:86
本文介绍了无法从MVC中存在外键的表中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的mvc应用程序中,我有2个表,名为: 与外键关系相关的明细(srNo,ID,工作),母版(ID,名称,计划)使用"ID"字段从明细传递到母版. "ID"字段是主表的主键. "srNo"字段是明细表的主键.

In my mvc application I have 2 tables named: detail(srNo, ID, work), master(ID, name,plan) that are related with foreign key relation ship from detail to master using "ID" field. "ID" field is primary key of master table. "srNo" field is primary key of detail table.

在"ID"字段中,这2个表与外键关系一起加入.

From the "ID" field, this 2 tables are joined with foreign key relation ship.

现在问题是: 在向数据库添加任何行时,我们首先在master表中创建条目,然后在details表中创建条目. 有时由于某些例外,当在主表中成功添加行但无法在明细表中添加行时.然后我要从主表执行回滚.

Now the Problem is: While adding any row to database, we are first make entry in master table , then in details table. And sometimes due to some exception, when row is succesfully added in master table but can not add in detail table. Then I want to perform rollback from master table.

但是当我要删除具有最近添加的ID值(grom linq to sql)的行时,该行已添加到主表中,这给了我一个例外,那就是外键实现船在那里...

But when I want to delete the row with recently added ID value (grom linq to sql), which is added in master table it is giving me exception that forign key realtion ship is there .....

那时明细表中没有该ID字段的行.

And at that time in detail table there is no row of that id field.

谢谢

推荐答案

我认为您需要将它们一起提交,以便它们在同一笔交易中.然后,无需编写回滚代码,因为如果详细信息失败,则不会插入主数据库. 尝试以下方法:

I think you need to submit both of them together so they are in the same transaction. Then there is no need to write rollback code as the master won't get inserted if the detail fails. Try this instead:

master objmaster= new master(); 
objmaster.id =count; 
objmaster.name= name1; 
.. 
objEntities.AddObject("master", objmaster); 
// == removed save changes call here ==
detail objDetail = new detail() 
// == no need to reselect master from the database, you already have it
// == so just assign it, and that will take care of the references/foreign-key
objDetail.master = objMaster; // Suppose I get any (format, null pointer exception here) 
objDetail.folow = sfields[0]; //In case of exception this below code will not be excecuted

objEntities.AddObject("detail", objDetail); 
// == save at the end ==
objEntities.SaveChanges(); 

这篇关于无法从MVC中存在外键的表中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆