我有一个包含三个表的数据库。用户,消息和提交。该网站启动,我可以登录并注册就好了当我发布消息时,我收到以下错误。
MySqlException:无法添加或更新子行:外键 约束失败(
)thewall
。messages
,CONSTRAINTfk_messages_users1
外键(user_id
)参考users
(UserId
)在更新时不执行任何操作(
查找错误,我知道它与多对一关系,即外键有关。但看了这个并倾倒了数据库100次。我需要另一双新鲜的眼睛,看看他们是否能发现它。
MessageFactory.cs
public void Add(Message Item)
{
using(IDbConnection dbConnection = Connection)
{
string Query = "INSERT INTO messages (MessageContent, PosterId, CreatedAt, UpdatedAt) VALUES (@MessageContent, @PosterId, NOW(), NOW())";
dbConnection.Open();
dbConnection.Execute(Query, Item);
}
}
有问题的表是这样设置的
MessageId
MessageContent
PosterId
Createdat
Updatedat
user_id <this is the foreign key> linking it to users.
MessagesController.cs
public IActionResult CreateMessage(Message model)
{
if(!CheckLogin())
{
return RedirectToAction("RegisterPage", "Users");
}
if(ModelState.IsValid)
{
model.PosterId = (int)HttpContext.Session.GetInt32("CurrUserId");
_messageFactory.Add(model);
return RedirectToAction("Index");
}
List<Message> AllMessages = _messageFactory.GetAllMessages();
ViewBag.CurrentUser = _userFactory.GetUserById((int)HttpContext.Session.GetInt32("CurrUserId"));
ViewBag.Messages = AllMessages;
return View("Index", model);
}
Any help would be greatly appriacted.