【问题标题】:Entity Framework Creates New Record in Table I Didn't Reference when Inserting Into Other Table实体框架在插入其他表时未引用的表中创建新记录
【发布时间】:2012-04-03 06:42:20
【问题描述】:

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

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();
    }

但是一旦发生这种情况,噗:我的 Users 表中的一条新记录与 ArticleComments 中的新记录一起出现。新用户记录中的所有信息都与该用户的现有记录重复 - 唯一的区别是主键 Id 的值。什么给了?

【问题讨论】:

  • ArticleComment 上的用户导航属性必须是虚拟的:public virtual User User { get; set; }
  • 如果我猜的话,它与User = currentUser, 行有关。检查对象 EntityState 以了解上下文对此的看法。

标签: sql asp.net-mvc entity-framework-4 duplicates


【解决方案1】:

除了我的评论之外,您还需要确保 _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,
};

【讨论】:

  • 非常感谢,先生。不知道为什么我首先尝试设置该属性...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多