在 Fluent NHibernate 中将 IUserType 映射到组件属性

发布于 2024-11-15 16:21:33 字数 416 浏览 2 评论 0原文

我正在尝试为州和国家/地区代码实现一个 IUserType ,这将允许我访问两个字母的代码(存储在数据库中的内容)以及全名。我正在遵循 NHibernate 3.0 Cookbook (p. 225) 中的示例,但我的问题是我的 StreetAddress 类当前在我的自动映射配置中映射为组件:

public override bool IsComponent(Type type)
{
    return type == typeof(StreetAddress);
}

将此类标识为组件,我不知道如何使用 IUserType 作为组件类的属性,因为该类没有显式映射。我无法告诉流畅的 NHibernate 使用 IUserType 规范。

I'm trying to implement an IUserType for states and country codes that will allow me to access both the two-letter code (what's stored in the database) as well as the full name. I'm following the example in the NHibernate 3.0 Cookbook (p. 225), but my problem is that my StreetAddress class is currently mapped as a component in my automapping configuration:

public override bool IsComponent(Type type)
{
    return type == typeof(StreetAddress);
}

With this class identified as a component, I don't know how I can use an IUserType for the component class's property, since that class isn't explicitly mapped. There's nowhere that I could tell fluent NHibernate to use the IUserType specification.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

养猫人 2024-11-22 16:21:33

@Firo 很接近,但事实证明有一个更简单的解决方案。这里有两个步骤。首先,我必须告诉 Fluent NHibernate 不要映射位于我的域层中的 StateCountry 类:

public override bool ShouldMap(Type type)
{
    return type.Name != "State" && type.Name != "Country";
}

接下来,我只需为 StateCountry 类创建约定 :代码>IUserType类。事实证明,这比 @Firo 建议的更容易:

public class CountryUserTypeConvention : UserTypeConvention<CountryType>
{
}

public class StateUserTypeConvention : UserTypeConvention<StateType>
{
}

这些 IUserTypes 的定义是从原始问题中引用的食谱中取出的,但如果您不想阅读它:

public class CountryType : GenericWellKnownInstanceType<Country, string>
{
    // The StateType is pretty much the same thing, only it uses "StateCode" instead of "CountryCode"
    private static readonly SqlType[] sqlTypes =
        new[] {SqlTypeFactory.GetString(2)};

    public CountryType()
        : base(new Countries(),
               (entity, id) => entity.CountryCode == id,
               entity => entity.CountryCode)
    {
    }

    public override SqlType[] SqlTypes
    {
        get { return sqlTypes; }
    }
}

那就得出来自GenericWellKnownInstanceType

[Serializable]
public abstract class GenericWellKnownInstanceType<T, TId> :
    IUserType where T : class
{
    private Func<T, TId, bool> findPredicate;
    private Func<T, TId> idGetter;
    private IEnumerable<T> repository;

    protected GenericWellKnownInstanceType(
        IEnumerable<T> repository,
        Func<T, TId, bool> findPredicate,
        Func<T, TId> idGetter)
    {
        this.repository = repository;
        this.findPredicate = findPredicate;
        this.idGetter = idGetter;
    }

    public Type ReturnedType
    {
        get { return typeof (T); }
    }

    public bool IsMutable
    {
        get { return false; }
    }

    public new bool Equals(object x, object y)
    {
        if (ReferenceEquals(x, y))
        {
            return true;
        }
        if (ReferenceEquals(null, x) ||
            ReferenceEquals(null, y))
        {
            return false;
        }
        return x.Equals(y);
    }

    public int GetHashCode(object x)
    {
        return (x == null) ? 0 : x.GetHashCode();
    }

    public object NullSafeGet(IDataReader rs,
                              string[] names, object owner)
    {
        int index0 = rs.GetOrdinal(names[0]);
        if (rs.IsDBNull(index0))
        {
            return null;
        }
        var value = (TId) rs.GetValue(index0);
        return repository.FirstOrDefault(x =>
                                         findPredicate(x, value));
    }

    public void NullSafeSet(IDbCommand cmd,
                            object value, int index)
    {
        if (value == null)
        {
            ((IDbDataParameter) cmd.Parameters[index])
                .Value = DBNull.Value;
        }
        else
        {
            ((IDbDataParameter) cmd.Parameters[index])
                .Value = idGetter((T) value);
        }
    }

    public object DeepCopy(object value)
    {
        return value;
    }

    public object Replace(object original,
                          object target, object owner)
    {
        return original;
    }

    public object Assemble(object cached, object owner)
    {
        return cached;
    }

    public object Disassemble(object value)
    {
        return value;
    }

    /// <summary>
    /// The SQL types for the columns
    /// mapped by this type.
    /// </summary>
    public abstract SqlType[] SqlTypes { get; }
}

这些类的存储库只是StateCountry 对象的一对ReadOnlyCollection。再次,来自食谱:

public class States : ReadOnlyCollection<State>
{
    // Truncated in the interest of brevity
    public static State Arizona = new State("AZ", "Arizona");
    public static State Florida = new State("FL", "Florida");
    public static State California = new State("CA", "California");
    public static State Colorado = new State("CO", "Colorado");
    public static State Oklahoma = new State("OK", "Oklahoma");
    public static State NewMexico = new State("NM", "New Mexico");
    public static State Nevada = new State("NV", "Nevada");
    public static State Texas = new State("TX", "Texas");
    public static State Utah = new State("UT", "Utah");

    public States() : base(new State[]
                               {
                                   Arizona, Florida, California, Colorado,
                                   Oklahoma, NewMexico, Nevada, Texas, Utah
                               }
        )
    {
    }
}

希望这对那里的人有帮助。

@Firo was close, but there turned out to be a much easier solution. There were two steps here. First, I had to tell Fluent NHibernate not to map the State and Country classes, which reside in my domain layer:

public override bool ShouldMap(Type type)
{
    return type.Name != "State" && type.Name != "Country";
}

Next, I simply had to create the conventions for the IUserType classes. This turned out to be easier than @Firo suggested:

public class CountryUserTypeConvention : UserTypeConvention<CountryType>
{
}

public class StateUserTypeConvention : UserTypeConvention<StateType>
{
}

The definition of those IUserTypes was pulled out of the cookbook referenced in the original question, but in case you don't want to read it:

public class CountryType : GenericWellKnownInstanceType<Country, string>
{
    // The StateType is pretty much the same thing, only it uses "StateCode" instead of "CountryCode"
    private static readonly SqlType[] sqlTypes =
        new[] {SqlTypeFactory.GetString(2)};

    public CountryType()
        : base(new Countries(),
               (entity, id) => entity.CountryCode == id,
               entity => entity.CountryCode)
    {
    }

    public override SqlType[] SqlTypes
    {
        get { return sqlTypes; }
    }
}

And that derives from GenericWellKnownInstanceType:

[Serializable]
public abstract class GenericWellKnownInstanceType<T, TId> :
    IUserType where T : class
{
    private Func<T, TId, bool> findPredicate;
    private Func<T, TId> idGetter;
    private IEnumerable<T> repository;

    protected GenericWellKnownInstanceType(
        IEnumerable<T> repository,
        Func<T, TId, bool> findPredicate,
        Func<T, TId> idGetter)
    {
        this.repository = repository;
        this.findPredicate = findPredicate;
        this.idGetter = idGetter;
    }

    public Type ReturnedType
    {
        get { return typeof (T); }
    }

    public bool IsMutable
    {
        get { return false; }
    }

    public new bool Equals(object x, object y)
    {
        if (ReferenceEquals(x, y))
        {
            return true;
        }
        if (ReferenceEquals(null, x) ||
            ReferenceEquals(null, y))
        {
            return false;
        }
        return x.Equals(y);
    }

    public int GetHashCode(object x)
    {
        return (x == null) ? 0 : x.GetHashCode();
    }

    public object NullSafeGet(IDataReader rs,
                              string[] names, object owner)
    {
        int index0 = rs.GetOrdinal(names[0]);
        if (rs.IsDBNull(index0))
        {
            return null;
        }
        var value = (TId) rs.GetValue(index0);
        return repository.FirstOrDefault(x =>
                                         findPredicate(x, value));
    }

    public void NullSafeSet(IDbCommand cmd,
                            object value, int index)
    {
        if (value == null)
        {
            ((IDbDataParameter) cmd.Parameters[index])
                .Value = DBNull.Value;
        }
        else
        {
            ((IDbDataParameter) cmd.Parameters[index])
                .Value = idGetter((T) value);
        }
    }

    public object DeepCopy(object value)
    {
        return value;
    }

    public object Replace(object original,
                          object target, object owner)
    {
        return original;
    }

    public object Assemble(object cached, object owner)
    {
        return cached;
    }

    public object Disassemble(object value)
    {
        return value;
    }

    /// <summary>
    /// The SQL types for the columns
    /// mapped by this type.
    /// </summary>
    public abstract SqlType[] SqlTypes { get; }
}

The repositories for these classes are just a pair of ReadOnlyCollection of the State and Country objects. Again, from the cookbook:

public class States : ReadOnlyCollection<State>
{
    // Truncated in the interest of brevity
    public static State Arizona = new State("AZ", "Arizona");
    public static State Florida = new State("FL", "Florida");
    public static State California = new State("CA", "California");
    public static State Colorado = new State("CO", "Colorado");
    public static State Oklahoma = new State("OK", "Oklahoma");
    public static State NewMexico = new State("NM", "New Mexico");
    public static State Nevada = new State("NV", "Nevada");
    public static State Texas = new State("TX", "Texas");
    public static State Utah = new State("UT", "Utah");

    public States() : base(new State[]
                               {
                                   Arizona, Florida, California, Colorado,
                                   Oklahoma, NewMexico, Nevada, Texas, Utah
                               }
        )
    {
    }
}

Hopefully this helps someone out there.

被你宠の有点坏 2024-11-22 16:21:33

我无法测试它,但使用约定应该是可能的

public class ComponentConvention : IComponentConvention, IComponentConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IComponentInspector> criteria)
    {
        criteria.Expect(x => x.Type == typeof(StreetAddress);
    }

    public void Apply(IComponentInstance instance)
    {
        instance.Properties.First(p => p.Name == "CountrCode").CustomType<MyUserType>();
    }
}

i couldnt test it, but it should be possible using a convention

public class ComponentConvention : IComponentConvention, IComponentConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IComponentInspector> criteria)
    {
        criteria.Expect(x => x.Type == typeof(StreetAddress);
    }

    public void Apply(IComponentInstance instance)
    {
        instance.Properties.First(p => p.Name == "CountrCode").CustomType<MyUserType>();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文