EF: C# Update or Insert if not exist

Posted by Unknown On Tuesday, June 6, 2017 0 comments

If your primary key is auto increment


public void InsertOrUpdate(Blog blog) 
{ 
    using (var context = new BloggingContext()) 
    { 
        context.Entry(blog).State = blog.BlogId == 0 ? EntityState.Added : EntityState.Modified;  
        context.SaveChanges(); 
    } 
}

If your primary key is not auto increment


public void InsertOrUpdate(Blog blog) 
{ 
    using (var context = new BloggingContext()) 
    { 
        var q = context.Blog.FirstOrDefault(x=>x.BlogId=blog.BlogId);        
        if (q != null)
            context.Entry(q).State = EntityState.Detached;
        context.Entry(blog).State = q == null ?EntityState.Added : EntityState.Modified; 
        context.SaveChanges(); 
    } 
}

0 comments:

Post a Comment