What Causes The INSERT statement conflicted with the FOREIGN KEY constraint?

前端 未结 2 1381
梦如初夏
梦如初夏 2020-12-16 01:09

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 se

2条回答
  •  余生分开走
    2020-12-16 01:15

    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.

提交回复
热议问题