问题
I have a composite key entity where one property is an int, and the other is an enum. The enum is currently mapping by string, but it needs to be int. I have an IUserTypeConvention that already does this, but it doesn't work for composite keys.
I have an Accept() method that correctly locates composite keys with enums in it, but I cannot figure out the Apply() code.
public class CompositeKeyEnumConvention : ICompositeIdentityConvention, ICompositeIdentityConventionAcceptance
{
public void Apply(ICompositeIdentityInstance instance)
{
}
public void Accept(IAcceptanceCriteria<ICompositeIdentityInspector> criteria)
{
criteria.Expect(x => HasEnumKey(x));
}
private bool HasEnumKey(ICompositeIdentityInspector x)
{
if (x.KeyProperties.Count() > 0)
{
foreach (IKeyPropertyInspector inspector in x.KeyProperties)
{
if (inspector.Type.GenericArguments.Count() != 1)
continue;
if (EnumConvention.IsInt32EnumType(inspector.Type.GenericArguments.First()))
return true;
}
}
return false;
}
}
The code for the enum convention that works is
public void Apply(IPropertyInstance instance)
{
instance.CustomType(instance.Property.PropertyType);
}
I just can't figure out how to do it for a composite key.
Thanks!
回答1:
like my other answer here only with reflection
public class CompositeKeyEnumConvention : ICompositeIdentityConvention
{
public void Apply(ICompositeIdentityInstance instance)
{
// when instance.KeyProperties. Count == 0 nothing happens
foreach (IKeyPropertyInstance inspector in instance.KeyProperties)
{
if (inspector.Type.GenericArguments.Count() != 1)
continue;
if (EnumConvention.IsInt32EnumType(inspector.Type.GenericArguments.First()))
{
var keymapping = (KeyPropertyMapping)inspector.GetType()
.GetField("mapping", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(inspector);
keymapping.Type = inspector.Type;
}
}
}
}
来源:https://stackoverflow.com/questions/8736057/how-can-i-make-composite-key-enums-use-int-in-fluent-nhibernate-with-a-conventio