Entity framework 4 – Code first

I haven’t got the time to update my previous article to the new CTP-addon for supporting Code-first (old name Code-only). My goal is to start covering this topic during this week, so stay tuned.

//Daniel

Updates to – Putting Entity framework 4 to use in a business architecture

This post only reflects some updates to my previous article: Putting Entity framework 4 to use in a business architecture.

I made a “minor” error in my EfDynamicProxyAssemblies that is consumed by my EfDataContractSerializer. The error which I know have corrected arised when I added an example to the client application, where I intended to read back the created wishlist(s) for a certain username. What happened was that the service used the overload of the EfEntityStore’s Query method that lets you specify string’s for memebers in the objectgraph to include in the select. The generated proxie than contained three entities: Wishlist, UserAccount and Wish, but my EfDynamicProxyAssemblies cleared the cached assemblies once the types were extracted. And the first time the dynamic proxie assembly was executed, the only contained type was UserAccount, hence WishList and Wish didn’t get extracted and registrered as a known type.

I have corrected the code and added some information about the custom EfDataContractSerializer attribute in the article.

Download the pdf

The complete code example can be found here.

I have also added some information about “eager loading”. So there is some new code and two new sub chapters.

Enjoy!

//Daniel

Putting Entity framework 4 to use in a business architecture

Updates have been made since version 1 of this article!

“>Read more about it here.

Finally I’m finished. I have been struggling with an intended sum-up of my latest post using Entity framework 4. It ended up with an document of about 40 pages. There is a lot of code in there so the number of pages could be a bit missleading (which of course depends on what you are seeking).

Download the pdf

The complete code example can be found here.

As always….. Have fun with it!

//Daniel

WCF DataContractSerializer problems with dynamic proxies in Entity framework 4

This article was produced for Beta 2 & CTP2

Download the code

I were having trouble with serialization of my entities over WCF using net.tcp binding when letting the ObjectContext create dynamic proxies. To solve the problem I hade to extend the DataContractSerializerOperationBehavior and provide it with the dynamic proxies as “Known types”.

I also had to create a custom attribute that I could mark my methods (service operations) so that my custom DataContractSerializerOperationBehavior is invoked “only when needed”.

It was as simple as that. I also created an class that listens for the AppDomain.AssemblyLoad event and keeps track of the dynamic proxy types.

So if you are having these problems, feel free to use the code.

You also have to decorate your entities with the Serializable- and DataContract attribute with IsReference=true. Also you have to mark the members that should be serialized in your entites with the DataMember attribute.

The Interface that defines my service
I only mark the methods that uses entities that has a dynamic proxy with my custom EfDataContractSerializer attribute.

[ServiceContract]
public interface ISecurityService : IService
{
    [OperationContract]
    [EfDataContractSerializer]
    ServiceResponse<UserAccount> SetupNewUserAccount(UserAccount userAccount);

    [OperationContract]
    [EfDataContractSerializer]
    ServiceResponse<UserAccount> GetUserAccountByCredentials(string username, string password);

    [OperationContract]
    [EfDataContractSerializer]
    ServiceResponse UpdateUserAccount(UserAccount userAccount);

    [OperationContract]
    ServiceResponse SetNewPassword(string username, string currentPassword, string newPassword);
}

EfDataContractSerializerAttribute – For decorationg methods in your service

[Serializable]
public class EfDataContractSerializerAttribute : Attribute, IOperationBehavior
{
    private readonly EfDataContractSerializerOperationBehavior _innerOperationBehavior;
    
    public EfDataContractSerializerAttribute()
    {
    }

    public EfDataContractSerializerAttribute(OperationDescription operation)
    {
        _innerOperationBehavior = new EfDataContractSerializerOperationBehavior(operation);
    }

    public EfDataContractSerializerAttribute(OperationDescription operation, DataContractFormatAttribute dataContractFormatAttribute)
    {
        _innerOperationBehavior = new EfDataContractSerializerOperationBehavior(operation, dataContractFormatAttribute);
    }

    public void Validate(OperationDescription operationDescription)
    {
        if (_innerOperationBehavior == null)
            return;

        (_innerOperationBehavior as IOperationBehavior).Validate(operationDescription);
    }

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        ReplaceDataContractSerializerOperationBehavior(operationDescription);
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
        ReplaceDataContractSerializerOperationBehavior(operationDescription);
    }

    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {
        if (_innerOperationBehavior == null)
            return;

        (_innerOperationBehavior as IOperationBehavior).AddBindingParameters(operationDescription, bindingParameters);
    }

    private void ReplaceDataContractSerializerOperationBehavior(OperationDescription description)
    {
        var operationBehavior = description.Behaviors.Find<DataContractSerializerOperationBehavior>();

        if (operationBehavior == null)
            return;

        description.Behaviors.Remove(operationBehavior);
        description.Behaviors.Add(new EfDataContractSerializerOperationBehavior(description));
    }
}

EfDataContractSerializerOperationBehavior – For populating the DataContractSerializer with known types

public class EfDataContractSerializerOperationBehavior : DataContractSerializerOperationBehavior
{
    public EfDataContractSerializerOperationBehavior(OperationDescription operation)
        : base(operation)
    {
    }

    public EfDataContractSerializerOperationBehavior(OperationDescription operation, DataContractFormatAttribute dataContractFormatAttribute)
        : base(operation, dataContractFormatAttribute)
    {
    }

    public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
    {
        return new DataContractSerializer(type, name, ns, MergeKnownTypesWithDynamicProxyTypes(knownTypes));
    }

    public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
    {
        return new DataContractSerializer(type, name, ns, MergeKnownTypesWithDynamicProxyTypes(knownTypes));
    }

    private static IEnumerable<Type> MergeKnownTypesWithDynamicProxyTypes(IEnumerable<Type> knownTypes)
    {
        var tmp = new HashSet<Type>();

        if (knownTypes != null)
            tmp.UnionWith(knownTypes);

        tmp.UnionWith(EfDynamicProxyAssemblies.GetTypes());

        return tmp;
    }
}

EfDynamicProxyAssemblies – For keeping track of currently generated dynamic proxies

public static class EfDynamicProxyAssemblies
{
    private static readonly object _lock = new object();
    private static readonly Dictionary<string, Assembly> _loadedAssemblies = new Dictionary<string, Assembly>();
    private static readonly HashSet<Assembly> _assembliesToExtract = new HashSet<Assembly>();
    private static readonly List<Type> _dynamixProxies = new List<Type>();

    static EfDynamicProxyAssemblies()
    {
        AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);
    }

    private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
    {
        if (args == null || args.LoadedAssembly == null || string.IsNullOrEmpty(args.LoadedAssembly.FullName))
            return;

        lock (_lock)
        {
            if ((args.LoadedAssembly.FullName).StartsWith("EntityFrameworkDynamicProxies") &&
                !_loadedAssemblies.ContainsKey(args.LoadedAssembly.FullName))
            {
                _loadedAssemblies.Add(args.LoadedAssembly.FullName, args.LoadedAssembly);
                _assembliesToExtract.Add(args.LoadedAssembly);
                //Types aren't generated yet, so we can't add them to _dynamixEntityProxies
            }
        }
    }

    public static IEnumerable<Type> GetTypes()
    {
        lock(_lock)
        {
            var types = _assembliesToExtract.SelectMany(a => a.GetTypes()).ToList();
            _dynamixProxies.AddRange(types);

            _assembliesToExtract.Clear();
        }

        return _dynamixProxies;
    }
}

Enjoy!

//Daniel

Entity framework 4 – How-to reuse mappings and add a Concurrency token

I’m working on a larger sample (I will write or do a screencast about this shortly) which uses a distributed solution with WCF and the Entity framework 4 Code-only approach. Doing this I wanted to add a Concurrency token so that EF would trap concurrency violations, e.g:

1. I fetch an object which becomes detached.
2. The same object (seen to business equality) gets fetched in some other part of the application.

We now have to different instances representing the same domain object.

3. The entity from step 2 is updated and persisted.
4. When the entity from step 1 is sent to the object context for update, EF uses the Concurrency token field and gets 0-rows affected.

How do I add an concurrency token?
1. Add a property in your entity, which is of datatype byte[].
2. Add mapping for the field, stating that the added field is the Concurrency token and of which type (timestamp or rowversion)

Since I want all my entities to have this I add the property to my Entity-baseclass. I also have defined a base mapping class that maps this and the Id property for my entities, so that I don’t have to specify this all the time.

The Entities

public abstract class Entity
{
    public virtual int Id { get; set; }

    public virtual byte[] ConcurrencyToken { 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; }

    public virtual string Firstname { get; set; }

    public virtual string Lastname { get; set; }
}

The mappings

[Serializable]
public abstract class EntityMapping<TEntity> : EntityConfiguration<TEntity>
    where TEntity : Entity
{
    protected EntityMapping()
    {
        HasKey(u => u.Id);
        Property(u => u.Id).IsIdentity();

        Property(u => u.ConcurrencyToken)
            .IsRequired()
            .IsConcurrencyToken()
            .HasStoreType("timestamp")
            .StoreGeneratedPattern = StoreGeneratedPattern.Computed;
    }
}
[Serializable]
public class UserAccountMapping : EntityMapping<UserAccount>
{
    public UserAccountMapping()
    {
        Property(u => u.Email)
            .IsRequired()
            .IsNotUnicode()
            .MaxLength = 150;

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

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

        Property(u => u.Firstname)
            .IsRequired()
            .IsUnicode()
            .MaxLength = 100;

        Property(u => u.Lastname)
            .IsRequired()
            .IsUnicode()
            .MaxLength = 100;
    }
}

//Daniel

Entity framework 4 – Code only – How-to change target names in the database table

For a couple of days ago I got the question of “my mappings doesn’t work”. I looked at it and found that the database tables were generated upfront and not by the ObjectContext. The columnnames had other names. Than how-do you solve this missmatch if you really do want to have separate namings? Using MapSingleType.

Personally, I let the context create the database and the tables, since I want the model to drive the database design.

The entity

[Serializable]
public class Car
{
    public string LicencePlate { get; set; }
    public int CountryCode { get; set; }
}

The mapping

[Serializable]
public class CarMapping : EntityConfiguration<Car>
{
    public CarMapping()
    {
        HasKey(c => new { c.CountryCode, c.LicencePlate });
        MapSingleType(c => 
            new
                {
                    TheCountryCode = c.CountryCode, 
                    TheLicencePlate = c.LicencePlate
                }).ToTable("dbo.TheCars");
    }
}

The result
Table: TheCars (you don’t have to use “ToTable”).
Columns:

  • TheCountryCode
  • TheLicencePlate

//Daniel

Entity framework 4 – Code-only, How-to map a combined PK

I got a question today of how to map an entity with a primarykey that is built up using two fields. The answer: using an anonymous type.

The entity

[Serializable]
public class Car
{
    public string LicencePlate { get; set; }
    public int CountryCode { get; set; }
}

The mapping

[Serializable]
public class CarMapping : EntityConfiguration<Car>
{
    public CarMapping()
    {
        HasKey(c => new {c.CountryCode, c.LicencePlate});
    }
}

//Daniel

Entity framework 4 – Part 5 – Validation using Data Annotations

This post is part of a series of post where I cover different aspects of the new version of Entity framework and the CTP features. I do focus on creating a POCO solutions, hence I don’t use the designer to generate my model.

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

Download the code.

This time I will look at validation using the “System.ComponentModel.DataAnnotations” lib. NOTE! That it doesn’t say “System.Data.Entity.DataAnnotations” or any other specific part of the .Net framework. It is a common lib that could be used in e.g ASP.Net MVC.

Specify the rules
Lets start with the rules. I have chosen to decorate my entities with attributes to specify the rules for them. This is as easy as:

1. Add reference to “System.ComponentModel.DataAnnotations”
2. Import namespace
3. Start decorating your classes.

This looks like:

[Serializable]
public class UserAccount
    : Entity
{
    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "UserAccountRequiredUsername", ErrorMessageResourceType = typeof(ModelValidationMessages))]
    public virtual string Username { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "UserAccountRequiredPassword", ErrorMessageResourceType = typeof(ModelValidationMessages))]
    public virtual string Password { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "UserAccountRequiredEmail", ErrorMessageResourceType = typeof(ModelValidationMessages))]
    public virtual string Email { get; set; }
}

I have not created any custom attribute to take care of specific validation like an “EmailAttribute”, but it can be done. I have chosen to go with resources, but you can go with simple errormessages which would look like:

[Required(AllowEmptyStrings = false, ErrorMessage="You must provide an username.")]
public virtual string Username { get; set; }

Validate an entity
In this example I’m performing the validation in my services. This is something that isn’t necessary. E.g if you are using the new MVC 2 the default modelbinder can handle the validation for you.

To fulfill “DRY” (Dont repeat yourself) I have created a base class for my services, which contains a helper-method that validates entities. The method is “ValidateEntity”. It returns an instance of my EntityValidationResult-class which contains the violations. I’m using this instance to determine if the entity should be persisted or not. The violations are passed back to the serviceconsumer via a ServiceResponse, so I don’t throw any ugly business exceptions.

public class SecurityService : Service, ISecurityService
{
    public SecurityService(IEntityStore entityStore)
        : base(entityStore)
    {
    }

    public ServiceResponse<UserAccount> SetupNewUserAccount(UserAccount userAccount)
    {
        var validationResult = ValidateEntity<UserAccount>(userAccount);

        if (!validationResult.HasViolations)
        {
            EntityStore.AddEntity(userAccount);
            EntityStore.SaveChanges();
        }

        return new ServiceResponse<UserAccount>(userAccount, validationResult);
    }
}

The ValidateEntity method is really simple, since it just consumes another object, my EntityValidator. The code for this looks like:

In the baseclass: “Service”:

protected EntityValidationResult ValidateEntity<T>(T entity)
    where T : IEntity
{
    return new EntityValidator<T>().Validate(entity);
}
public class EntityValidator<T> where T : IEntity
{
    public EntityValidationResult Validate(T entity)
    {
        var validationResults = new List<ValidationResult>();
        var vc = new ValidationContext(entity, null, null);
        var isValid = Validator.TryValidateObject(entity, vc, validationResults);

        return new EntityValidationResult(validationResults);
    }
}

The EntityValidator just consumes classes found in the System.ComponentModel.DataAnnotations library and returns eventual violations by wrapping them in my EntityValidationResult-class.

[Serializable]
public class EntityValidationResult
{
    public IList<ValidationResult> Violations { get; private set; }
    public bool HasViolations
    {
        get { return Violations.Count > 0; }
    }

    public EntityValidationResult(IList<ValidationResult> violations = null)
    {
        Violations = violations ?? new List<ValidationResult>();
    }
}

Handle the violations
Since I’m just fiddling a bit I have a simple consoleapplication which only outputs the errors:

private static void IfFailedServiceOperationInformUser<T>(ServiceResponse<T> serviceResponse)
{
    if (serviceResponse.Status == ServiceResponseStatuses.Succeeded)
        return;

    Console.WriteLine("Service failed!");

    if (serviceResponse.ValidationResult.HasViolations)
    {
        Console.WriteLine("Violations are:");
        foreach (var violation in serviceResponse.ValidationResult.Violations)
        {
            foreach (var member in violation.MemberNames)
                Console.WriteLine("\t+" + member);

            Console.WriteLine("\t" + violation.ErrorMessage);
        }
    }
}

Thats it for now. As always you can download a complete example, which has evolved since part 1 of this post-series.

//Daniel

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

Entity framework 4 – Part 3 – Adding pluralization support to a non strongly typed ObjectContext.

Part 1 – Getting started
Part 2 – Relationships between non public members

This is a post that continues on my previous post about how you could be building a ObjectContext in Entity Framework 4, without having them to be strongly typed. There’s no EDMX model etc. in your solutions.

This time I’m just going to show you have you can consume the PluralizationService to automatically get pluralized strings. I’m using it to get pluralized tablenames from my Entity framework-based, Entity store.

Download a complete example here. Ensure to update the config-file.

To pluralize the tables I need to consume the PluralizationService from Microsoft. This is really easy. Just call the factorymethod “CreateService” and provide for which culture you wan’t it to handle strings for and then let it pluralize a string.

var pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en"));

string pluralized = pluralizer.Pluralize("UserAccount"); //Results in the string "UserAccounts"

Pluralize tablenames
This is done in my RegisterEntity method in my custom ObjectContextBuilder. The RegisterEntity method is there to let you register EntitySets in the ContextBuilder as well as register mapping information for entities; so that when the builder creates an ObjectContext, this information is passed along to the context.

/// <summary>
/// Registers the entity by setting up a set and configurations for it.
/// If no configuration is passed, only a Set will be registrered.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="entityConfiguration">The entity configuration.</param>
public void RegisterEntity<TEntity>(EntityConfiguration<TEntity> entityConfiguration = null)
    where TEntity : class, IEntity
{
    var pluralizedSetName = _pluralizer.Pluralize(typeof (TEntity).Name);

    RegisterSet<TEntity>(pluralizedSetName);
    if (entityConfiguration != null)
        Configurations.Add(entityConfiguration);
}

Above you can see that we are consuming the PluralizationService instance that has been created in the constructor. The SetName matches the name of the Entity but it is now is pluralized which leads to that the tables that are generated in the database, will have names that are pluralized.

The PluralizationService is for now found in System.Data.Entity.Design.

Download a complete example here. Ensure to update the config-file.

//Daniel