我目前正在将数据库用于A级计算项目。如问题所述,当我尝试将数据保存到数据库(UserGameKey)时,我当前遇到错误。数据库有两列; GameKey(这是唯一密钥)和UserGameKeyID(这是与身份数据库中用户ID相等的外键)。
这个问题已经有好几个人遇到过-但是,给出的答案几乎总是表明这个问题的出现是因为外键在其派生的初始数据库中还不存在。就我而言,这是不正确的-至少似乎并非如此-因此每次我尝试将新记录保存到UserGameKey时,都会出现错误;
INSERT语句与FOREIGN KEY约束冲突 “ FK_UserGameKey_Project_With_IdentityUser_UserGameKeyID”
发生。
这是我的/play.cshtml,试图从中保存数据;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Razor;
using Project_With_Identity.Hubs;
using Microsoft.AspNetCore.Identity;
using Project_With_Identity.Areas.Identity.Data;
using Project_With_Identity.Models;
namespace Project_With_Identity.Pages
{
public class PlayModel : PageModel
{
private readonly UserManager<Project_With_IdentityUser> _userManager;
private readonly SignInManager<Project_With_IdentityUser> _signInManager;
private readonly UserGameKeyContext _gamekeycontext;
public PlayModel(
UserManager<Project_With_IdentityUser> userManager,
SignInManager<Project_With_IdentityUser> signInManager,
UserGameKeyContext gameKeyContext)
{
_userManager = userManager;
_signInManager = signInManager;
_gamekeycontext = gameKeyContext;
}
[BindProperty]
public string gameKey { get; set; }
public async Task<IActionResult> OnPostCreateGame()
{
await createGame();
UserGameKey NewUserGameKey = new UserGameKey { };
NewUserGameKey.UserGameKeyID = _userManager.GetUserId(User);
NewUserGameKey.GameKey = gameKey;
if(_userManager.FindByIdAsync(NewUserGameKey.UserGameKeyID) != null)
{
try
{
_gamekeycontext.UserGameKeys.Add(NewUserGameKey);
_gamekeycontext.SaveChanges();
}
catch (Exception e)
{
Console.Write(e.Message);
return Redirect("./Error");
}
}
var URL = "/Game/" + gameKey + ".cshtml";
return Redirect(URL);
}
//edited for brevity.
}
}
这是我的UserGameKey模型;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Project_With_Identity.Areas.Identity.Data;
namespace Project_With_Identity.Models
{
public class UserGameKey
{
[Key]
public string GameKey { get; set; }
[ForeignKey("Project_With_IdentityNavi")]
public string UserGameKeyID { get; set; }
public Project_With_IdentityUser Project_With_IdentityNavi { get; set; }
}
}
我的主要重点是让/play.cshtml将新的Gamekey和当前登录的用户ID保存到UserGameKey数据库中,以便用户可以使用同一个Gamekey多次访问同一个游戏。
任何建议将不胜感激,谢谢!