EF - AddOrUpdate

CSharp · Console

/Program.cs

// @nuget: EntityFramework

using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

public class Program
{
	public static void Main()
	{
		InsertData();
		
		Author authorData; 
		
		using (var context = new BookStore())
		{
            authorData = context.Authors
        		.FirstOrDefault();
			
			FiddleHelper.WriteTable(context.Authors.ToList());
			
			authorData.FirstName = "Alan";
		}
		using (var context = new BookStore())
		{
            List<Author> list = new List<Author>()
			{
				authorData,
				new Author() { FirstName = "Steve", LastName = "John" }
			};
			
			foreach(var author in list)
			{
				context.Entry(author).State = author.AuthorId == 0 ?
					EntityState.Added :
					EntityState.Modified;

        		context.SaveChanges();
			}
			
			FiddleHelper.WriteTable(context.Authors.ToList());
		}
		
	}
	
	public static void InsertData()
	{
		using (var context = new BookStore())
		{
			var Authors = new List<Author>
			{
				new Author() {FirstName = "Mark", LastName = "Cuban"},
				new Author() {FirstName = "Andy", LastName = "Holloway"}
			};
			
		    context.Authors.AddRange(Authors);
			context.SaveChanges();
			
		}
	}
	
	public class BookStore : DbContext
    {
        public BookStore() : base(FiddleHelper.GetConnectionStringSqlServer())
        {
        }

        public DbSet<Author> Authors { get; set; }
    }

    public class Author
	{
    	public int AuthorId { get; set; }
    	public string FirstName { get; set; }
		public string LastName { get; set; }
	}
}
;