我喜欢我在这篇博文(http://marekblotny.blogspot.com/2009/04/conventions-after-rewrite.html)中看到的模式,作者在应用约定之前检查是否已经进行了表名更改。
public bool Accept(IClassMap target)
{
//apply this convention if table wasn't specified with WithTable(..) method
return string.IsNullOrEmpty(target.TableName);
}
我用于字符串长度的约定接口是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);
}
}
我没有看到IProperty公开任何告诉我属性是否已经设置的内容。这可能吗?
TIA, Berryl
答案 0 :(得分:1)
.WithLengthOf()
在生成XML映射时,将“更改”(Action<XmlElement>
)添加到要应用的更改列表中。不幸的是,该字段为private
并且没有属性可以访问更改列表,因此我担心(目前)无法检查属性映射是否已应用WithLengthOf
。
答案 1 :(得分:1)
在找到更好的替代方案之前,您可以使用HasAttribute("length")
。
答案 2 :(得分:0)
在代码中澄清Stuart和Jamie所说的内容,这是有效的:
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);
}
}