[英]How to check if a value already exists in my database and show a validation message in ASP.NET & Entity Framework
[英]Entity framework - how to not insert new value if that value exists already
我正在使用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向上
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.