简体   繁体   中英

Entity framework - how to not insert new value if that value exists already

I am writing a blog website with MVC 4. I have the following action method in my CommentController to add comment to a article. A comment has a navigation property - author(identified by email address). What I am trying to do is if the email address of the author has already existed in database, I only insert new comment. If it's a new email address, then new author needs to be created as well.

--------Below is my Create action--------

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

--------Below is my Comment class--------

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

    }

Thank you all

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
}

This assumes your myDb has a table called Authors (which I think it does) and you may need to adjust the boolean Exists lambda to correctly match the AuthorId up

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM