How can I make composite key enums use int in fluent nhibernate with a convention?

不羁岁月 提交于 2019-12-14 02:25:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!