是什么原因导致与国外KEY约束相冲突的INSERT语句? [英] What Causes The INSERT statement conflicted with the FOREIGN KEY constraint?

查看:172
本文介绍了是什么原因导致与国外KEY约束相冲突的INSERT语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code为我以前的工作,但我不知道是什么了已造成此错误。我唯一​​的猜测是,当我尝试创建一个球员,团队的数据被送回球队表和它试图复制,但由于TeamId是独一无二的,因此这个错误。

This code has worked for me before but i am not sure anymore what has been causing this error. My only guess is that when i try to create a Player, the Team Data is being sent back to Team table and its trying to duplicate but since TeamId is unique hence this error.

错误

INSERT语句冲突与外键约束FK_dbo.Players_dbo.Teams_TeamId。冲突发生于数据库网络,表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>

该如何解决这个问题?

How can resolve this error?

推荐答案

您应该尝试完成实体,如队伍,为您的播放器的实体。尤其是外键。

You should try to complete entities like teams for your player entity. Especially foreign keys.

[HttpPost]
    public ActionResult Create(Player model)
    {
        if (ModelState.IsValid)
        {
            using (var db = new EfDb())
            {
                //Since you have the username cached, you can check the local EF cache for the object before hitting the db.
                //var userProfile = db.UserProfiles.Single(u => u.UserName == User.Identity.Name);
                var userProfile = db.UserProfiles.Local.SingleOrDefault(u => u.UserName == User.Identity.Name) 
                               ?? db.UserProfiles.SingleOrDefault(u => u.UserName == User.Identity.Name);
                if (userProfile != null)
                {
                    var player = new Player
                                     {
                                         UserProfile = userProfile,                                             
                                         ....
                                         ....                                              
                                     };  
                    player.TeamId = 5;                      
                    db.Players.Add(player);                          

                    db.SaveChanges();
                }
            }
        }
        PopulateTeamsDropDownList(model.TeamId);
        return View(model);
    }

和确保从视图下拉列表中是必需的,发送正确的值后的方法。

And make sure the Dropdown from your view is Required and send correct value to the post method.

这篇关于是什么原因导致与国外KEY约束相冲突的INSERT语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆