上载图像-ForeignKey冲突
本文关键字:冲突 -ForeignKey 图像 上载 | 更新日期: 2023-09-27 18:30:04
im试图使用jquery插件上传我的图像并将其插入我的数据库。
我的问题是两张桌子之间的关系。
INSERT语句与FOREIGN KEY约束冲突"FK_Image_User"。数据库中发生冲突"Mydatabase",表"dbo.User",列"Id"。
这是我的代码:
在控制器中:
获取:
public ActionResult Manage(int id = 0)
{
User u= db.MyUsers.Find(id);
if (u== null)
{
return HttpNotFound();
}
return View(u);
}
上传我有这个代码:
private void UploadWholeFile(HttpContext context, List<FilesStatus> statuses, Image img, User u)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
for (int i = 0; i < context.Request.Files.Count; i++)
{
var file = context.Request.Files[i];
var fullpath = StorageRoot + Guid.NewGuid() + Path.GetFileName(file.FileName);
file.SaveAs(fullpath);
string fullName = Path.GetFileName(file.FileName);
statuses.Add(new FilesStatus(fullName, file.ContentLength, fullpath));
SqlCommand cmd;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append("insert into Image(MyFileName,Id_User)");
sql.Append("values (@MyFileName, @Id_User)");
cn.Open();
cmd = new SqlCommand(sql.ToString(), cn);
cmd.Parameters.Add("@MyFileName", SqlDbType.VarChar).Value = fullpath;
cmd.Parameters.Add("@Id_User", SqlDbType.Int).Value = u.Id;
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
Id_User与dbo之间存在外键关系。用户表,该表不包含要插入的ID。在dbo中插入值。用户表,或者检查并更正您在Id_User中插入的值。