违反了PRIMARY KEY约束.无法插入重复键

本文关键字:插入 约束 PRIMARY KEY | 更新日期: 2023-09-27 18:02:51

我使用List对象来包含与我的主表有一对多关系的从表中的项。主表的PK作为从表的FK字段。

然而,当记录试图保存

时,我得到这个错误
Violation of PRIMARY KEY constraint 'PK_ClearinghousePartners'. Cannot insert duplicate 
key in object 'dbo.ClearinghousePartners'. The duplicate key value is (0)

Primary Table Model

仅供参考-这个表包含大量字段,所以我只是显示List

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

Secondary Table Model

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字段可以创建,然后插入到ClearinghousePartners对象的AgtTransId字段。

agenttransmission.LastChangeDate = DateTime.Now;
agenttransmission.LastChangeOperator = Security.GetUserName(User);
db.AgentTransmission.Add(agenttransmission);
db.SaveChanges(); //Exception thrown here
<<p> 视图/strong>
<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>

违反了PRIMARY KEY约束.无法插入重复键

重复键值为(0)

我猜你的表没有设置为自动填充你的主键值作为identity属性。声明应该像这样:

ClearinghousePartners int primary key PK_ClearinghousePartners identity

您需要为ClearinghousePartners.[PrimaryKey]指定一个新的未使用的值,或者使该列成为自动生成的列(在sql server - What RDBMS Are You using ?中称为Identity列)