EF - AsNoTracking

CSharp · Console

/Program.cs

// @nuget: EntityFramework
// @nuget: EntityFramework.SqlServerCompact
// @nuget: Microsoft.SqlServer.Compact
// @nuget: Z.EntityFramework.Extensions

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();
		
		using (var context = new BookStore())
		{
			context.Database.Log = Console.WriteLine;
			
			var authors = context.Authors
				.AsNoTracking()
				.ToList();
		}
		
	}
	
	public static void InsertData()
	{
		using (var context = new BookStore())
		{
			for(int i = 1; i < 1000; i++)
			{
				Author author = new Author()
		    	{
		        	Name = "Author " + i,
		        };
				
				context.Authors.Add(author);
			}

		    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 Name { get; set; }
	}
}
;