我正在使用List对象来包含与我的主表具有一对多关系的辅助表中的项目。主表的PK用作辅助表的FK字段。

但是,当记录尝试保存时出现此错误

Violation of PRIMARY KEY constraint 'PK_ClearinghousePartners'. Cannot insert duplicate
key in object 'dbo.ClearinghousePartners'. The duplicate key value is (0)


主表模型

仅供参考-该表包含大量字段,因此我只显示List

public partial class AgentTransmission
{
    .
    .
    public virtual List<ClearinghousePartners> ClearinghousePartners { get; set; }
}


辅助表模型

public partial class ClearinghousePartners
{
    public int Id { get; set; }
    public string ClearingHouseName { get; set; }
    public string TradingPartnerName { get; set; }
    public Nullable<System.DateTime> StartDate { get; set; }
    public int AgtTransId { get; set; } //FK field corresponds to 'Id' on AgentTransmission

    public virtual AgentTransmission AgentTransmission { get; set; }
}


控制者

当模型回发到控制器以保存时,在此代码区域中引发异常。这是AgentTransmission对象是全新的实例,需要将其添加到数据库中。 ClearinhousePartners集合中的每个项目也是如此。

每个都是全新的ClearinghousePartners项目,其中IdAgtTransId字段没有值。我需要首先保存AgentTransmission对象,以便可以创建它的Id字段,然后将其插入AgtTransId对象中的ClearinghousePartners字段中。

agenttransmission.LastChangeDate = DateTime.Now;
agenttransmission.LastChangeOperator = Security.GetUserName(User);
db.AgentTransmission.Add(agenttransmission);
db.SaveChanges(); //Exception thrown here


视图

<fieldset id="ClearinghousePartners">
    <legend>Clearinghouse Partners</legend>
    <center>
        <table>
            <thead>
                <th>Clearinghouse Name</th>
                <th>Trading Partner Name</th>
                <th>Start Date</th>
            </thead>
            <tbody>
                @for (int i = 0; i < Model.ClearinghousePartners.Count(); i++)
                {
                    <tr align="center">
                        @Html.HiddenFor(model => model.ClearinghousePartners[i].Id)
                        @Html.HiddenFor(model => model.ClearinghousePartners[i].AgtTransId)
                        <td>@Html.TextBoxFor(model => model.ClearinghousePartners[i].ClearingHouseName, new { style = "width: 100px" })</td>
                        <td>@Html.TextBoxFor(model => model.ClearinghousePartners[i].TradingPartnerName, new { style = "width: 100px" })</td>
                        <td>@Html.TextBoxFor(model => model.ClearinghousePartners[i].StartDate, new { style = "width: 100px" })</td>
                    </tr>
                }
            </tbody>
        </table>
    </center>
</fieldset>

最佳答案

重复键值为(0)


我猜您的表未设置为自动将主键值填充为identity属性。声明应如下所示:

ClearinghousePartners int primary key PK_ClearinghousePartners identity

08-15 23:34