我有一个复合键实体,其中一个属性是int,另一个是枚举。枚举当前是按字符串映射的,但它必须是int。我有一个已经执行此操作的IUserTypeConvention,但它不适用于复合键。
我有一个Accept()方法,可以正确地找到包含枚举的复合键,但我无法弄清楚Apply()代码。
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;
}
}
有效的枚举约定的代码是
public void Apply(IPropertyInstance instance)
{
instance.CustomType(instance.Property.PropertyType);
}
我无法弄清楚如何为复合键做这件事。
谢谢!
答案 0 :(得分:1)
就像我的另一个答案here只有反射
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;
}
}
}
}