Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架-如果新值已经存在,如何不插入该值_C#_Asp.net_Asp.net Mvc_Entity Framework - Fatal编程技术网

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

C# 实体框架-如果新值已经存在,如何不插入该值,c#,asp.net,asp.net-mvc,entity-framework,C#,Asp.net,Asp.net Mvc,Entity Framework,我正在用MVC4写一个博客网站。在我的CommentController中有以下操作方法来向文章添加注释。注释具有导航属性-author(通过电子邮件地址标识)。 我想做的是,如果作者的电子邮件地址已经存在于数据库中,我只插入新的评论。如果是新的电子邮件地址,那么还需要创建新的作者 --------下面是我的创建操作-------- --------下面是我的评论课-------- 谢谢大家 var authors = myDb.Authors; if((comment.AuthorId !=

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

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

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

谢谢大家

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

我的答案中有一个很好的粗略推断-基本上您需要检查AuthorId是否a)有效(不是null或0)通过使用循环或linq lambdaen,它不存在于Authors表中,这非常有用。非常感谢,没问题-如果对您有效,请记住将其标记为答案;)此解决方案存在争用条件,因为在完成检查
authors.Exists(a=>a.AuthorID==comment.AuthorID)
之后,其他请求可能会在插入之前插入同一作者
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
}