Using custom C# attributes to select Fluent conventions
Suppose you have sets of Fluent conventions that apply to specific groups of mappings, but not to all of them.
My thought here was, I'll create custom C# attributes that I can apply to the Fluent *Map classes - and write conventions that determine acceptance by inspecting the *Map class to see if the custom attribute was applied.
That way, I can select groups of conventions and apply them to various mappings by just tagging them with a custom attri开发者_运维问答bute - [UseShortNamingConvention], etc.
I'm new to NHibernate (and Fluent, and C# for that matter) - is this approach possible?
And is it sane? :-)
Thanks!
Yes it is! Ive actually done something similiar but went with Marker Interfaces instead (INotCacheable, IComponent), but Marker Interface or Attribute, should't be that much of a difference.
When applying your conventions, just check for the presence of your attribute and ur good :)
EDIT:
Adding some code samples
public class MyMappingConventions : IReferenceConvention, IClassConvention
{
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Key.Column(instance.EntityType.Name + "ID");
instance.LazyLoad();
instance.Inverse();
instance.Cascade.SaveUpdate();
if ((typeof(INotCacheable).IsAssignableFrom(instance.Relationship.Class.GetUnderlyingSystemType())))
return;
instance.Cache.ReadWrite();
}
public void Apply(IClassInstance instance)
{
instance.Table(instance.EntityType.Name + "s");
//If inheriting from IIMutable make it readonly
if ((typeof(IImmutable).IsAssignableFrom(instance.EntityType)))
instance.ReadOnly();
//If not cacheable
if ((typeof(INotCacheable).IsAssignableFrom(instance.EntityType)))
return;
instance.Cache.ReadWrite();
}
}
精彩评论