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

前端之家收集整理的这篇文章主要介绍了c# – 什么原因INSERT语句与FOREIGN KEY约束冲突?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这段代码对我有用,但我不知道是什么导致了这个错误.我唯一的猜测是,当我尝试创建一个播放器时,团队数据被发送回团队表并尝试重复,但是由于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方法发送正确的值.

猜你在找的C#相关文章