c# - 如何摆脱mvc中的外键异常
问题描述
我的项目中有一个模块,在一个功能中我有一个文本框,我在其中输入丢失的注释并使用按钮保存它,但是我保存数据的表有一个外键,我得到以下异常
我的代码如下
public ActionResult SetBreakageNote(int id, string MissNote, int charge)
{
var Rdetail = new ReservationDetail();
if (ModelState.IsValid)
{
Rdetail.ReservationID = id;
Rdetail.Description = MissNote;
Rdetail.ChargeType = charge;
db.Insert(Rdetail);
}
return RedirectToAction("Index");
}
我的观点
@model IEnumerable<RoomTypeView>
<div class="row">
@foreach (var item in Model)
{
<div class="col-3">
<div class="row">
<div class="col-8">
<div class="inventory my-1">
<textarea class="form-control breakage" placeholder="Enter Breakage Note" rows="1"></textarea>
</div>
</div>
<div class="col-4">
<button type="button" class="btn btn-default breakage" data-brid="@item.ReservationID"><i class="fa fa-file-invoice" style="color:red;"></i></button>
</div>
</div>
</div>
}
</div>
$('.breakage').click(function () {
$.post("@Url.Action("SetBreakageNote", "HouseKeeping")", { id: $(this).data('brid'), MissNote: $('.breakage').val(), charge: @((int)ChargeTypeEnum.Breakage) });
});
这是我得到的例外
INSERT 语句与 FOREIGN KEY 约束“FK_ReservationDetails_Reservation”冲突。冲突发生在数据库“CavalaV3DB”、表“dbo.Reservation”、列“ReservationID”中
ReservationID 是 Reservation 表的外键。
请在这件事上给予我帮助
解决方案
在插入数据之前,foreign key
字段中的值必须首先存在于另一个表中。您必须构建包含第一个表的表,Primary Key
然后您可以在下拉列表中填充它们,您需要先选择以保存数据。
最好的处理方法是在下拉列表
foreign key
中绑定它们并设置所需的属性other table's View
推荐阅读
- volttron - Volttron 平台在设置期间不接受 IP 地址
- pygame - 你如何解决:“AttributeError:'Boundary'对象没有属性'rect'”?
- javascript - XHR 多部分文件上传 Spring Boot 问题
- jquery - 将 Ajax jQuery 转换为 Axios
- javascript - 当我滑动手指时,试图让它在 div 中更改页面
- c++ - 用户定义的构造函数重载与参数超类的重载没有参数匹配
- wordpress - 从最近的帖子中获取值
- module - Joomla 中的模块只调用一次
- java - Hibernate:删除一对多/多对一失败
- haproxy - haproxy - 第 7 层健康检查失败