在本网站中,用户可以使用用户名和密码进行注册,也可以对文章发表评论。这些模型非常简单:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool IsAdmin { get; set; }
public DateTime JoinDate { get; set; }
public string AvatarPath { get; set; }
public string EmailAddress { get; set; }
}
public class ArticleComment
{
public int Id { get; set; }
public int ArticleId { get; set; }
public int UserId { get; set; }
public string CommenterName { get; set; }
public string Message { get; set; }
public DateTime CommentDate { get; set; }
public User User { get; set; }
}
当使用代码优先创建数据库时, Entity Framework 正确地在 ArticleComment 上的 UserId 和 User 上的 Id 之间建立了外键关系。
这是我在用户发布新评论时的代码:
public JsonResult SubmitComment(int articleId, string comment)
{
var response = new JsonResponse();
var currentUser = _userRepository.GetUserByUsername(User.Identity.Name);
//...
var newComment = new ArticleComment
{
ArticleId = articleId,
CommentDate = DateTime.Now,
CommenterName = currentUser.Username,
UserId = currentUser.Id,
User = currentUser,
Message = comment,
};
try
{
_articleRepository.Insert(newComment);
}
catch (Exception e)
{
response.Success = false;
response.AddError("newComment", "Sorry, we could not add your comment. Server error: " + e.Message);
return Json(response);
}
response.Success = true;
response.Value = newComment;
return Json(response);
}
构成 newComment 对象的值似乎都是正确的,并且我的 Article 存储库类中的 Insert 方法是直接切中要点的:
public void Insert(ArticleComment input)
{
DataContext.ArticleComments.Add(input);
DataContext.SaveChanges();
}
但是一旦发生这种情况,poof: 我的Users 表中的一条新记录会与 ArticleComments 中的新记录一起出现。新用户记录中的所有信息均与该用户的现有记录重复 - 唯一的区别是主键 Id 的值。给出了什么?
最佳答案
除了我的评论之外,您还需要确保 _userRepository
和 _articleRepository
使用相同的 DbContext 实例。
要么这样,要么你可以尝试这个:
var newComment = new ArticleComment
{
ArticleId = articleId,
CommentDate = DateTime.Now,
CommenterName = currentUser.Username,
UserId = currentUser.Id,
// User = currentUser, let the UserId figure out the User, don't set it yourself.
Message = comment,
};
关于sql - Entity Framework 在插入其他表时未引用的表中创建新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9988316/