实体框架-如何不插入新值,如果该值已经存在

本文关键字:如果 存在 新值 框架 何不 插入 实体 | 更新日期: 2023-09-27 17:52:54

我正在用MVC 4写一个博客网站。我在我的CommentController中有以下动作方法来向文章添加评论。注释有一个导航属性-作者(通过电子邮件地址标识)。我想做的是,如果作者的电子邮件地址已经存在于数据库中,我只插入新的评论。如果它是一个新的电子邮件地址,那么还需要创建一个新的作者。

--------下面是我的创建操作--------

     public ActionResult Create(Comment comment)
            {
                if (ModelState.IsValid)
                {
                    comment.CreatedDate = DateTime.Now;
                    myDb.Comments.Add(comment);
                    myDb.SaveChanges();
                    return RedirectToAction("Details", "Blog", new {id = comment.BlogId });
                }
                return View(comment);
            }

--------下面是我的评论类--------

public class Comment
    {
        [Key]
        public int CommentId { get; set; }
        [Required(ErrorMessage="Please enter your comment")]
        public string CommentContent { get; set; }
        public DateTime CreatedDate { get; set; }
        [Required]
        public int AuthorId { get; set; }
        public virtual Author Author { get; set; }
        [Required]
        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

谢谢大家

实体框架-如何不插入新值,如果该值已经存在

var authors = myDb.Authors;
if((comment.AuthorId != null || comment.AuthorId !=0) && !authors.Exists(a=>a.AuthorID == comment.AuthorId))
{
   //do your creation of new Author and then post the article
}
else//author exists
{
   //just post article
}

这假设您的myDb有一个名为Authors的表(我认为它确实如此),您可能需要调整布尔Exists lambda以正确匹配AuthorId up