Using my own attributes with Subsonic SimpleRepository
I have been looking for an ORM of late and SubSonic with its SimpleRepository appears to be the solution I'm looking for.
Is there a way to use my own attributes or ones from System.ComponentModel
to drive some of the generati开发者_开发知识库on of the SQL? I want to keep my model/domain objects clean of third-party stuff.
I wouldn't recommend that but this can be done.
Create your own attributes that match SubSonics attributes (like OrmIgnore
instead of SubSonicIgnore
, the still have to Implement SubSonic.SqlGeneration.Schema.IClassMappingAttribute
or SubSonic.SqlGeneration.Schema.IPropertyMappingAttribute
or SubSonic.SqlGeneration.Schema.IRelationMappingAttribute
Look at this code from SubSonic.Core\Extensions\Object.cs to get an idea what's happening
public static ITable ToSchemaTable(this Type type, IDataProvider provider)
{
...
var typeAttributes = type.GetCustomAttributes(typeof(IClassMappingAttribute), false);
foreach (IClassMappingAttribute attr in typeAttributes)
{
if (attr.Accept(result))
{
attr.Apply(result);
}
}
...
// Now work with attributes
foreach (IPropertyMappingAttribute attr in attributes.Where(x => x is IPropertyMappingAttribute))
{
if (attr.Accept(column))
{
attr.Apply(column);
}
}
....
}
your Apply implementation should modify the schema to do what you want. Like this one (from SubSonicDefaultSettingAttribute):
public void Apply(IColumn column)
{
column.DefaultSetting = DefaultSetting;
}
You should check out the SubSonic source and mark every custom attribute as obsolete
[Obsolete("Use OrmIgnore instead", true)]
[AttributeUsage(AttributeTargets.Property)]
public class SubSonicIgnoreAttribute : Attribute { }
There are some direct references to the attributes (that don't use the interface) that you will need to fix.
And you will have to look for string references
private static bool ColumnIsIgnored(object[] attributes)
{
foreach (var att in attributes)
{
if (att.ToString().Equals("SubSonic.SqlGeneration.Schema.SubSonicIgnoreAttribute"))
{
return true;
}
}
return false;
}
with
private static bool ColumnIsIgnored(object[] attributes)
{
foreach (var att in attributes)
{
if (att.ToString().EndsWith("OrmIgnoreAttribute"))
{
return true;
}
}
return false;
}
精彩评论