这段代码以前对我有用,但我不确定是什么导致了这个错误。我唯一的猜测是,当我尝试创建玩家时,团队数据被发送回团队表并尝试复制,但由于 TeamId 是唯一的,因此出现此错误。
错误
INSERT 语句与 FOREIGN KEY 约束“FK_dbo.Players_dbo.Teams_TeamId”冲突。冲突发生在数据库“Web”、表“dbo.Teams”、列“TeamId”中。该语句已终止。
播放器
public class Player
{
...
...
[HiddenInput(DisplayValue = false)]
[ForeignKey("Team")]
public int TeamId { get; set; }
public virtual Team Team { get; set; }
...
}
团队
public class Team
{
[Key]
[HiddenInput(DisplayValue = false)]
public int TeamId { get; set; }
....
public virtual ICollection<Player> Players { get; set; }
}
控制器
//
// GET: /Player/
[HttpGet]
public ActionResult Create()
{
PopulateTeamsDropDownList();
return View();
}
//
// POST: /Player/
[HttpPost]
public ActionResult Create(Player model)
{
if (ModelState.IsValid)
{
using (var db = new EfDb())
{
var userProfile = db.UserProfiles.Single(u => u.UserName == User.Identity.Name);
if (userProfile != null)
{
var player = new Player
{
UserProfile = userProfile,
....
....
};
db.Players.Add(player);
db.SaveChanges();
}
}
}
PopulateTeamsDropDownList(model.TeamId);
return View(model);
}
private void PopulateTeamsDropDownList(object selectedTeams = null)
{
var teamsQuery = from d in _iService.Teams
orderby d.Name
select d;
ViewBag.TeamID = new SelectList(teamsQuery, "TeamId", "Name", selectedTeams);
}
看法
<div class="editor-label">
@Html.LabelFor(model => model.TeamId, "Pick Your Team")
</div>
<div class="editor-field">
@Html.DropDownList("TeamId", String.Empty)
@Html.ValidationMessageFor(model => model.TeamId)
</div>
如何解决此错误?