Project: EntityFramework


EntityFramework CodeFirst is really fast to use in simple scenario.

The derived DbContext:
public class FinancialDbContext 
	: DbContext
{
	public FinancialDbContext(string nameOrConnectionString)
		: base(nameOrConnectionString)
	{
	}

	public IDbSet<Customer> CustomerSet
	{
		get { return Set<Customer>(); }
	}

	public IDbSet<Order> OrderSet
	{
		get { return Set<Order>(); }
	}

	protected override void OnModelCreating(DbModelBuilder modelBuilder)
	{
		modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
	}
}

And the test class:
[TestClass]
public class FinancialDbContextTest
{
	public FinancialDbContextTest()
	{
		Database.SetInitializer(new CreateDatabaseIfNotExists<FinancialDbContext>());
	}

	[TestMethod]
	public void AddAndRetrieveCustomer()
	{
		var id = Guid.NewGuid();

		using (var context = CreateContext())
		{
			context.CustomerSet.Add(new Customer { Id = id, Name = "Bill" });
			context.SaveChanges();
		}

		using (var context = CreateContext())
		{
			var customer = context.CustomerSet.Single(c => c.Id == id);
			Assert.AreEqual("Bill", customer.Name);
		}
	}

	[TestMethod]
	public void AddCustomerAndOrder()
	{
		var id = Guid.NewGuid();

		using (var context = CreateContext())
		{
			var customer = new Customer { Id = id, Name = "Bill" };
			context.CustomerSet.Add(customer);

			var order = new Order { Id = Guid.NewGuid(), Name = "Banana", Price = 100, Customer = customer };
			context.OrderSet.Add(order);
				
			context.SaveChanges();
		}

		using (var context = CreateContext())
		{
			var customer = context.CustomerSet.Include(c => c.OrderList).Single(c => c.Id == id);
			Assert.AreEqual(1, customer.OrderList.Count());
		}
	}

	private FinancialDbContext CreateContext()
	{
		return new FinancialDbContext("FinancialConnection");
	}
}

At the end, the Domain class:
public class Customer : UniqueEntity<Guid>
{
	public string Name { get; set; }

	public ICollection<Order> OrderList { get; private set; }
}

Last edited Oct 31, 2011 at 5:29 PM by teoarch, version 3

Comments

No comments yet.