Entity framework 4 – Part 4 – Autoregister Entitymappings

This post is part of a serie of posts where I have been fiddeling a bit with Entity framework 4 Beta 2 and extension CTP2. The example code has evolved during the writing of this series and the goal has been to create infrastructure for persisting my entities without the need of Entity framework designers, attributes etc.

Part 1 – Getting started
Part 2 – Relationships between non public members
Part 3 – Adding pluralization support to a non strongly typed ObjectContext.

Download the code.

For this post I have made the EfEntityStore-class non-abstract, so that you can consume it directly. I have also implemented a method that Auto-registers your EntityMapping-classes. So to get entities stored in your database you need to:

1. Define a connection string
2. Create your entity classes
3. Create classes that defines the mapping for your entities
4. Create an instance of the EfEntityStore and register your mappings and you’r done.
5. Consume it.

Step 1 – Define connectionstring
Note! You don’t need to create the database. The entitystore will do this for you when you call:
EnsureCleanDatabaseExists or EnsureDatabaseExists.

<connectionStrings>
  <add name="Test" connectionString="Data Source=.\sqlexpress;Initial Catalog=Christmas;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

Step 2 – Create entities
I have choosen to have a baseclass for all my entities.

[Serializable]
public abstract class Entity : IEntity
{
    public virtual int Id { get; set; }
}

[Serializable]
public class UserAccount
    : Entity
{
    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    public virtual string Email { get; set; }
}

Step 3 – Create entitymapping classes
For ease the autoregistration in Step 4 I have choosen to create a “dummy interface” that I implement in all my mapping classes, but it isn’t necessary if you don’t will use the generic autoregistration of your mappings.

public interface IChristmasEntityMapping
{
}

[Serializable]
public class UserAccountMapping : EntityConfiguration<UserAccount>, IChristmasEntityMapping
{
    public UserAccountMapping()
    {
        HasKey(u => u.Id);
        Property(u => u.Id).IsIdentity();

        Property(u => u.Email)
            .IsRequired()
            .IsNotUnicode()
            .MaxLength = 150;

        Property(u => u.Username)
            .IsRequired()
            .IsUnicode()
            .MaxLength = 20;

        Property(u => u.Password)
            .IsRequired()
            .IsUnicode()
            .MaxLength = 20;
    }
}

Step 4 & 5
Create an EntityStore instance and register the mappings. Then your done and you can start consuming it.

using(var es = new EfEntityStore("Test")) //Test is the name of the connection string
{
	es.MapEntities<IChristmasEntityMapping>();
	
	es.EnsureCleanDatabaseExists(); //Creates a new database.

	var userAccount =
		new UserAccount
			{
				Username = "littleben",
				Password = "ilovesnow",
				Email = "ben@thelittles.com"
			};

	es.SaveChanges();
}

In the donwloadable code I have implemented more entities and shown how StructureMap can help you with setting up the entitystore and a service.

Download the code and have fun with it.

The code below is not necessary, it only shows how you would use StructureMap to create an Entitystore and a service that consumers it.

public static class IoCContainer
{
	private static readonly Container _container;

	static IoCContainer()
	{
		_container = new Container();

		RegisterEntityStore();
		RegisterServices();

		//Debug.WriteLine(_container.WhatDoIHave());
	}

	private static void RegisterEntityStore()
	{
		_container.Configure(x => x
			.ForRequestedType<IEntityStore>()
			.CacheBy(InstanceScope.Singleton)
			.TheDefault.Is.OfConcreteType<EfEntityStore>()
			.WithCtorArg("connectionStringName").EqualTo("Test")
			.OnCreation(store => store.MapEntities<IChristmasEntityMapping>()));
	}

	private static void RegisterServices()
	{
		_container.Configure(x => x
			.ForRequestedType<ISecurityService>()
			.TheDefault.Is.OfConcreteType<SecurityService>()); //No need to specify cTor args since it will AutoMap IEntityStore from above
	}

	public static T Resolve<T>()
	{
		return _container.GetInstance<T>();
	}
}

//Daniel

About these ads

2 thoughts on “Entity framework 4 – Part 4 – Autoregister Entitymappings

  1. Pingback: Entity framework 4 – Part 5 – Validation using DataAnnotations « Daniel Wertheim

  2. Pingback: Entity Framework – Code Only Looking Good (part 2) | Jason Rowe

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s