Blog on development in general, and specifically on .NET. Created and maintained by Ricardo Peres.
Since version 6, Entity Framework Code First allows the injection of custom conventions. These conventions define rules that will be applied by default to all mapped entities and properties, unless explicitly changed.
The conventions API includes a couple of interfaces: IConvention (marker only, should always be included), IConceptualModelConvention<T> (for the conceptual space of the model) and IStoreModelConvention<T> (for the store, or physical, side of the model). Worthy of mention, there is also a convenience class, Convention, that allows access to all mapped types and properties and doesn’t override any of the other conventions, and also TypeAttributeConfigurationConvention<T>, for tying a convention to a custom attribute. Some of the included attributes leverage these interfaces to configure some aspects of the mappings at design time, other configuration needs to be done explicitly in an override of OnModelCreating.
Entity Framework permits using a column for distinguishing between different types, when the Table Per Class Hierarchy / Single Table Inheritance pattern (please see Entity Framework Code First Inheritance for more information) is used for mapping a hierarchy of classes to a single table, as part of “soft delete” solutions, or, less known, for differentiating between multiple tenants. This column is called a discriminator.
In order to configure an entity to use a discriminator column, there is no out of the box attribute, so we must resort to code configuration:
Because there’s really no need to keep repeating this code, let’s implement an attribute for indicating a discriminator column in an entity:
As you can see, the DiscriminatorAttribute attribute can only be applied to a class, at most once. This makes sense, because most likely you will only have a single discriminator column per entity:
You need to specify both a column name and a discriminator value, which can be of any type, usually, a string or an integer.
Now, let’s write a custom convention that knows how to handle our custom attribute and perform the mapping:
WARNING! DYNAMICS AND REFLECTION AHEAD!
PROCEED WITH CAUTION!
This class uses a bit of dynamics and reflection because types are not known at compile time, and hence we cannot use generics directly. Because the Apply method will be called multiple times, we need to keep track of which entities have already been processed by this convention, so as to avoid reprocessing them. We need to pass it the instance of DbModelBuilder, because otherwise our custom convention would have no way to apply the mapping, but I think it is a reasonable trade off.
Et voilà! In order to make use of it, we need to register the convention in OnModelCreating:
And that’s it! Happy conventions!
When you use a discriminator column, that is, a column that holds a value that tells Entity Framework what type the row refers to, or what restriction it shall use when querying the entity, you cannot map this column as a property in your entity.
For example, imagine you want to use “soft deletes”, that is, use a database column to represent the “deleted” state of a record instead of actually physically deleting it from the table; you might have an IS_DELETED column of some integer type, that would hold either a 1 or a 0, depending on whether the record is deleted (1) or not (0). In that case, you would build a mapping like this in OnModelCreating:
However, you won’t be able to have a corresponding IsDeleted property in the MySoftDeletableEntity, because Entity Framework will throw an exception complaining about it. It is somewhat sad, because it might be useful to refer to it, but that’s the way it is.
A result transformer, in NHibernate, is some class that implements the IResultTransformer interface:
Most query APIs, except LINQ, support specifying a result transformer. So, what is a result transformer used for? Just what the name says: it turns the values obtained from a query into some object. Normally, we just let NHibernate transform these values into instances of our entities, but we may want to do something different, either because we haven’t mapped some class that we want to use, or because we are not returning all of the entity’s properties, etc.
NHibernate includes some result transformers:
- AliasToBeanResultTransformer: allows to transform a result to a user specified class which will be populated via setter methods or fields matching the alias names;
- AliasToBeanConstructorResultTransformer: identical to AliasToBeanResultTransformer, but we specify a constructor for creating new instances of the target class;
- AliasToEntityMapResultTransformer: returns a dictionary where the keys are the aliases and the values the corresponding columns;
- AliasedTupleSubsetResultTransformer: ignores a tuple element if its corresponding alias is null;
- CacheableResultTransformer: used to transform tuples to a value(s) that can be cached;
- DistinctRootEntityResultTransformer: for joined queries, returns distinct root entities only;
- PassThroughResultTransformer: just returns the row as it was obtained from the database;
- RootEntityResultTransformer; returns the root entity of a joined query;
All of these can be obtained from static properties in class NHibernate.Transform.Transformers. NHibernate implicitly uses some of these, for example, LINQ queries always use DistinctRootEntityResultTransformer.
It is easy to build our own transformer. Have a look at the following example:
The TransformTuple method is the one used to turn each returned record into an instance of something. TransformList is called at the end, when all the records have been processed.
The ExpressionResultTransformer class allows us to select which indexes, in the database record, map to which properties in some entity. For our convenience, it offers a number of options to construct an instance (type, constructor + parameters and delegate). We would use it like this:
OK, so, I already showed how we can get the SQL that was generated from a LINQ query. Of course, we can do the same for both HQL and Criteria APIs as well (QueryOver is just a wrapper around Criteria, mind you).
So, for HQL (and SQL), it goes like this:
You can pass any implementation if IQuery, such as one produced from ISession.CreateQuery() or ISession.CreateSQLQuery(). The static field is merely for performance reasons.
As for Criteria:
And finally, QueryOver, just a small wrapper around the Criteria version:
Hope you find this useful!
The .NET ISupportInitialize interface is used when we want to support staged initialization for objects. Its BeginInit method is called when initialization is about to start and EndInit when it is finished.
If we want, it is easy to add support for it in NHibernate. An option would be:
- BeginInit is called when the object is instantiated, like when NHibernate has loaded a record from the database and is about to hydrate the entity, and immediately after the Id property is set;
- EndInit is called after all properties are set.
We do this by using a custom interceptor, like we have in the past. We start by writing a class that inherits from EmptyInterceptor, and implements the listener interface for the PostLoad event, IPostLoadEventListener:Then, before creating a session factory, we need to register it in the Configuration instance: Now, if your entity implements ISupportInitialize, NHibernate will automagically call its methods at the proper time. As simple as this!
As you may know, NHibernate knows how to generate the database for you from its model. Any of the supported databases will do.
What you may not know is that you can simply generate the SQL scripts that would be used to either generate the database from scratch or just update it to match the model as it is. For that you use the SchemaExport and SchemaValidator classes.
SchemaValidator takes a Configuration instance and basically throws an exception if, when its Validate method is called, the database does not match the model.
SchemaExport has far more options; it can:
- Create or drop a database model based on the entity model;
- Output the SQL to a file, either executing it at the same time or not;
- Execute the SQL to another arbitrary database connection;
- Execute a custom action after each line of the generated SQL script.
This time, I will be talking about integrating Unity with Managed Extensibility Framework (MEF). You can find the other posts in the series here (how to use Unity in a web application), here (adding Interfaces), here (registration by convention), here (injecting values), here (extensions), here (aspect-oriented programming), here (dependency injection) and the first one here (introduction).
The Managed Extensibility Framework (MEF) has been around since the release of .NET 4.0, and even before as a beta, stand-alone package. Basically, it provides an extensible mechanism for detecting and loading plugins. It’s easier to use than the similarly-named Managed Add-In Framework (MAF), and even if it’s not so feature-rich (it doesn’t support sandboxing, for once), unlike MAF, it is well alive!
So, what does MEF offer that can be of use to Unity? Well, MEF knows how to locate exports/plugins from a number of locations, like assemblies and file system directories. It’s just a matter of finding the exports we’re interested in and registering them with Unity.
An export in MEF is some class that is decorated with an ExportAttribute (technically speaking, this is just when using the Attributed Programming Model, since .NET 4.5 there is also the Convention-Based Programming Model). This attribute allows specifying the type to export (ContractType) and also the contract name (ContractName). This matches closely the Unity/IoC concept of contract type and name.
A couple of helper functions for picking up the export’s contract type and name, by leveraging the ReflectionModelServices class:
This will return a collection of key-value pairs, where the key is the contract name and the value the contract type; this is so there can be multiple contract names for a given contract type. After we have this, it’s just a matter of iterating the results and registering each occurrence:
So, given the following contract and implementations:
We can obtain a specific contract type implementation given it’s name:
And also all implementations of the contract that were found:
This can be enhanced in a couple of ways:
- Use a Unity extension to automatically find and register exports at runtime;
- Make use of MEF metadata to tell Unity which lifetime managers to use, and other useful properties, such as the default implementation for the contract type.
As usual, I’m looking forward for your comments!
In the past, I had to ask for confirmation before a form was actually submitted; the native way to ask for confirmation is through the browser’s confirm function, which basically displays a user-supplied message and two buttons, OK and Cancel. I wrapped it in a custom reusable validation control, which I am providing here:
A sample usage without any target control might be:
And if you want to specifically validate a control’s value:
When submitting your form, you will get a confirmation prompt similar to this (Chrome):
This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
This is a problem similar to the one with native id generators. Basically, because there are different versioning strategies – timestamp, counter, native, etc, – NHibernate needs to issue a SELECT after a versioned entity is INSERTEd or UPDATEd. While this wouldn’t be necessary when NHibernate manages the version on the “client side”, like:
But not if the version is handled on the database side, like when using SQL Server’s ROWVERSION/TIMESTAMP columns or Oracle’s ORA_ROWSCN pseudo-columns. In these cases, NHibernate needs to issue a SELECT after each INSERT or UPDATE:
This breaks batching, because it needs to be done immediately after each INSERT/UPDATE.
I started cross posting to my MVP blog, but you can continue following just this one because it will always be updated.