NHibernate Courant Modifications / Conventions
-
03-07-2019 - |
Question
J'aime le motif que j'ai vu dans ce blog ( http: //marekblotny.blogspot.com/2009/04/conventions-after-rewrite.html ), où l'auteur vérifie si une modification du nom de la table a déjà été effectuée avant d'appliquer une convention.
public bool Accept(IClassMap target)
{
//apply this convention if table wasn't specified with WithTable(..) method
return string.IsNullOrEmpty(target.TableName);
}
L'interface de convention que j'utilise pour une longueur de chaîne est IProperty:
public class DefaultStringLengthConvention: IPropertyConvention
{
public bool Accept(IProperty property) {
//apply if the string length hasn't been already been specified
return ??; <------ ??
}
public void Apply(IProperty property) {
property.WithLengthOf(50);
}
}
Je ne vois pas où IProperty expose quoi que ce soit qui me dit si la propriété a déjà été définie. Est-ce possible?
TIA, Berryl
La solution 3
Pour clarifier dans le code ce que Stuart et Jamie disent, voici ce qui fonctionne:
public class UserMap : IAutoMappingOverride<User>
{
public void Override(AutoMap<User> mapping) {
...
const int emailStringLength = 30;
mapping.Map(x => x.Email)
.WithLengthOf(emailStringLength) // actually set it
.SetAttribute("length", emailStringLength.ToString()); // flag it is set
...
}
}
public class DefaultStringLengthConvention: IPropertyConvention
{
public bool Accept(IProperty property) {
return true;
}
public void Apply(IProperty property) {
// only for strings
if (!property.PropertyType.Equals(typeof(string))) return;
// only if not already set
if (property.HasAttribute("length")) return;
property.WithLengthOf(50);
}
}
Autres conseils
.WithLengthOf()
ajoute une " modification " (Action<XmlElement>
) à la liste des modifications à appliquer lors de la génération du mappage XML. Malheureusement, ce champ est private
et il n’existe aucune propriété permettant d’accéder à la liste de modifications. Je crains donc qu’il n’existe (actuellement) aucun moyen de vérifier si une carte de propriété a été appliquée WithLengthOf
.
Jusqu'à ce qu'une meilleure alternative se présente, vous pouvez utiliser HasAttribute("length")
.