Project: Entity.Framework.5.Code.First

Create a database and read/write data using Entity Framework 5:
void Main()
{
	const string ConnectionString = @"Server=(localdb)\v11.0;Database=EyeOpen.LinqPad.Ef;Trusted_Connection=True";
	
	using (var dbContext = new FinancialDbContext(ConnectionString))
	{
		dbContext.Database.DeleteIfExistsAndCreate();
		dbContext.CustomerRepository.Add(new Customer { Name = "Bill" });
		dbContext.SaveChanges();
	}
	
	using (var dbContext = new FinancialDbContext(ConnectionString))
	{
		dbContext.CustomerRepository.Single().Dump();
	}
}
}

namespace EyeOpen.Data
{	
	public class FinancialDbContext
		: DbContext
	{
		public FinancialDbContext(string connectionString)
			: this(DbProviderFactories.GetFactory("System.Data.SqlClient"), connectionString)
		{
		}
		
		public FinancialDbContext(DbProviderFactory factory, string connectionString)
			: base(CreateConnection(factory, connectionString), true)
		{
		}
		
		public IDbSet<Customer> CustomerRepository
		{
			get { return base.Set<Customer>(); }
		} 
		
		protected override void OnModelCreating(DbModelBuilder modelBuilder)
		{
			modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
		}		

		private static DbConnection CreateConnection(DbProviderFactory factory, string connectionString)
		{
			var connection = factory.CreateConnection();
			connection.ConnectionString = connectionString;
			return connection;
		}		
	}
	
	public static class DatabaseExtensions
	{
		public static void DeleteIfExistsAndCreate(this System.Data.Entity.Database database)
		{
			if (database.Exists())
			{
				database.Delete();
			}
			
			database.Create();
		}		
	}
}

namespace EyeOpen.Domain
{
	public class Customer
		: Entity
	{
		public string Name { get; set; }
	}
	
	public abstract class Entity
	{
		public Entity()
		{
			Id = Guid.NewGuid();
		}
		
		public Guid Id { get; set; }
	}

Last edited May 3, 2012 at 12:09 PM by teoarch, version 3

Comments

No comments yet.