【问题标题】:Fluent NHibernte Alterations / Conventions流畅的 NHibernte 更改/约定
【发布时间】:2009-04-30 15:45:03
【问题描述】:

我喜欢我在这篇博文 (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, 浆果

【问题讨论】:

    标签: fluent-nhibernate conventions


    【解决方案1】:

    .WithLengthOf() 将“更改” (Action&lt;XmlElement&gt;) 添加到更改列表中,以便在生成 XML 映射时应用。不幸的是,该字段是private,并且没有访问更改列表的属性,所以恐怕(目前)无法检查属性映射是否已应用WithLengthOf

    【讨论】:

    • 认为这可能是交易;我不介意为字符串长度组添加约定,但很多情况都是一次性的,真正由类驱动。因此,如果 EmployeeNumber 字符串长度应为 6 个字符,则它是一个字段的 EmployeeNumberStringLengthConvention 或 DefaultStringLengthConvention 中的 if 语句。感谢您的快速响应。
    【解决方案2】:

    在出现更好的替代方案之前,您可以使用HasAttribute("length")

    【讨论】:

    • 这已经足够了,但它不起作用。我已经有几周没有更新 FNH 了——这是最近的更新吗?属性可能不是“长度”吗?感谢您的回复。
    • Berryl,如果您使用 SetAttribute,HasAttribute 应该可以工作。从修订版 458 开始,WithLengthOf 将“长度”属性存储在名为 columnProperties 的集合中。 SetAttribute 存储在 extendedProperties 中,这也是 HasAttribute 所在的位置。据我所知,SetAttribute/HasAttribute 一直以这种方式工作,因此它可能适用于您使用的任何版本。
    【解决方案3】:

    为了在代码中阐明 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多