Nea*_*alR 3 c# sql entity-framework entity-framework-4.1 asp.net-mvc-3
我正在使用一个List对象来包含我的主表与其一对多关系的辅助表中的项目.在PK主表中的作为FK在次级表字段.
但是,当记录尝试保存时,我收到此错误
Violation of PRIMARY KEY constraint 'PK_ClearinghousePartners'. Cannot insert duplicate
key in object 'dbo.ClearinghousePartners'. The duplicate key value is (0)
Run Code Online (Sandbox Code Playgroud)
主表模型
仅供参考 - 此表包含大量字段,因此我只是展示了 List
public partial class AgentTransmission
{
.
.
public virtual List<ClearinghousePartners> ClearinghousePartners { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
二级表模型
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; }
}
Run Code Online (Sandbox Code Playgroud)
调节器
当模型发回到控制器以保存异常时会抛出代码的这个区域.这是一个AgentTransmission对象是全新的并且需要添加到数据库的实例.对于ClearinhousePartners集合中的每个项目也是如此.
每个都是全新的ClearinghousePartners项目,没有值Id和AgtTransId字段的值.我需要AgentTransmission首先保存对象,以便Id可以创建它的字段,然后将其插入到对象的AgtTransId字段中ClearinghousePartners.
agenttransmission.LastChangeDate = DateTime.Now;
agenttransmission.LastChangeOperator = Security.GetUserName(User);
db.AgentTransmission.Add(agenttransmission);
db.SaveChanges(); //Exception thrown here
Run Code Online (Sandbox Code Playgroud)
视图
<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>
Run Code Online (Sandbox Code Playgroud)
重复键值为(0)
我猜你的表没有设置为自动将主键值填充为identity属性.声明应如下所示:
ClearinghousePartners int primary key PK_ClearinghousePartners identity
Run Code Online (Sandbox Code Playgroud)