Multi-rack unique FluentNHibernate automap constraint through convention

Does FluentNHibernate support the automatic creation of a unique multi-column constraint through convention?

I can easily create a single, single constraint:

public void Apply(IPropertyInstance instance)
{
    if(instance.Name.ToUpper().Equals("NAME"))
        instance.Unique();
}

With eligibility criteria for searching only types ReferenceEntity.

Now I have an object for which I want to create a restriction on several columns. I planned to decorate the properties of an entity with an attribute to indicate that they are part of the same unique key, that is:

public class Foo : Entity
{
    [Unique("name_parent")]
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }

    [Unique("name_parent")]
    public virtual Bar Parent { get; set; }
}

And accept these attributes and create unique objects in all fields that have the same unique key.

IProperyConvention Unique (), .

Update

, :

var propertyInfo = ((PropertyInstance)(instance)).EntityType.GetMember(instance.Name).FirstOrDefault();

if (propertyInfo != null)
{
    var attributes = propertyInfo.GetCustomAttributes(false);

    var uniqueAttribute = attributes.OfType<UniqueAttribute>().FirstOrDefault();

    if (uniqueAttribute != null)
    {
        instance.UniqueKey(uniqueAttribute.Key);
    }
}

, instance.UniqueKey(...) ( ), (pgsql);

ADD CONSTRAINT foo_name_key UNIQUE(name);

ADD CONSTRAINT name_parent UNIQUE(name, bar);

2

Override() AutoMap :

.Override<Foo>(map => {
    map.Map(x => x.Name).UniqueKey("name_parent");
    map.Map(x => x.Description);
    map.References(x => x.Parent).UniqueKey("name_parent");
})

-mapper, . , , .

+3
2

, 2 . AttributePropertyConvention, - IReferenceConvention. :

public class UniqueAttribute : Attribute
{
    public UniqueAttribute(string uniqueKey)
    {
        UniqueKey = uniqueKey;
    }

    public string UniqueKey { get; set; }

    public string GetKey()
    {
        return string.Concat(UniqueKey, "Unique");
    }
}

:

public class UniquePropertyConvention : AttributePropertyConvention<UniqueAttribute>
{
    protected override void Apply(UniqueAttribute attribute, IPropertyInstance instance)
    {
        instance.UniqueKey(attribute.GetKey());
    }
}

, , :

public class UniqueReferenceConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        var p = instance.Property.MemberInfo;

        if (Attribute.IsDefined(p, typeof(UniqueAttribute)))
        {
            var attribute = (UniqueAttribute[])p.GetCustomAttributes(typeof(UniqueAttribute), true);
            instance.UniqueKey(attribute[0].GetKey());
        }
    }
}

, .

+4

.... ;)

+1

All Articles