gpt4 book ai didi

sql - Entity Framework 在插入其他表时未引用的表中创建新记录

转载 作者:行者123 更新时间:2023-12-04 05:51:43 26 4
gpt4 key购买 nike

在本网站,用户可以使用用户名和密码进行注册,也可以对文章发表评论。这些模型非常简单:

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 对象的值似乎都是正确的,并且我的文章存储库类中的 Insert 方法是直截了当的:
    public void Insert(ArticleComment input)
{
DataContext.ArticleComments.Add(input);
DataContext.SaveChanges();
}

但是一旦发生这种情况,噗:我的用户表中的新记录与文章评论中的新记录一起出现。新用户记录中的所有信息都从该用户的现有记录中复制 - 唯一的区别是主键 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com