加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 什么原因INSERT语句与FOREIGN KEY约束冲突?

发布时间:2020-12-15 04:11:39 所属栏目:百科 来源:网络整理
导读:这段代码对我有用,但我不知道是什么导致了这个错误.我唯一的猜测是,当我尝试创建一个播放器时,团队数据被发送回团队表并尝试重复,但是由于TeamId是唯一的,因此这个错误. 错误 The INSERT statement conflicted with the FOREIGN KEY constraint “FK_dbo.Pla
这段代码对我有用,但我不知道是什么导致了这个错误.我唯一的猜测是,当我尝试创建一个播放器时,团队数据被发送回团队表并尝试重复,但是由于TeamId是唯一的,因此这个错误.

错误

The INSERT statement conflicted with the FOREIGN KEY constraint “FK_dbo.Players_dbo.Teams_TeamId”. The conflict occurred in database “Web”,table “dbo.Teams”,column ‘TeamId’. The statement has been terminated.

播放机

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>

如何解决这个错误?

解决方法

您应该尝试为您的玩家实体完成像团队这样的实体.特别是外键.
[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);
    }

并确保您的视图中的“下拉列表”是必需的,并向post方法发送正确的值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读