首页 > 解决方案 > 如何摆脱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 表的外键。

请在这件事上给予我帮助

标签: c#jqueryasp.net-mvc

解决方案


在插入数据之前,foreign key字段中的值必须首先存在于另一个表中。您必须构建包含第一个表的表,Primary Key然后您可以在下拉列表中填充它们,您需要先选择以保存数据。

最好的处理方法是在下拉列表foreign key中绑定它们并设置所需的属性other table's View


推荐阅读