NHibernate属性映射:列和公式

时间:2009-11-26 12:58:29

标签: nhibernate properties formula usertype

当我从被检查表中映射列时,我这样做:

<property name="InstanceName" type="MyNameUserType, MyApp.MyNamespace">
   <column name="Name"/>
   <column name="Name2"/>
</property>

如何使属性映射使用公式的sql查询检索的数据初始化UserType?

<property name="InstanceName" type="MyNameUserType, MyApp.MyNamespace" formula="(...)"/>

因“错误的列数”而失败。

提前致谢!

2 个答案:

答案 0 :(得分:1)

MyUserNameType应该是类级映射,以便您可以将SQL函数的结果映射到类。请参阅这两篇文章以获得一些可能的帮助:

  1. 类和SQL函数示例:http://thoughtspam.spaces.live.com/blog/cns!253515AE06513617!478.entry

  2. NHibernate映射与公式映射示例: http://thoughtspam.spaces.live.com/blog/cns!253515AE06513617!477.entry

答案 1 :(得分:1)

我是迈克尔引用的文章的作者。我不知道哪些人仍然感兴趣,我不确定它是否适用于最新的NHibernate。 这是一个新的链接:http://thoughtspam.wordpress.com/2007/12/19/nhibernate-property-with-formula/

示例,使用Northwind ...

映射:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="PropertyFormulaExample.Shipper, PropertyFormulaExample" table="Shippers" lazy="false" >
        <id name="ShipperID" column="ShipperID" unsaved-value="0">
            <generator class="native" />
        </id>
        <property name="CompanyName" column="CompanyName" />
        <property name="Phone" column="Phone" />
    </class>
</hibernate-mapping>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="PropertyFormulaExample.Order, PropertyFormulaExample" table="Orders" lazy="false">
        <id name="OrderID" column="OrderID" unsaved-value="0">
            <generator class="native" />
        </id>
        <property name="CustomerID" column="CustomerID" />
        <property name="ShipVia" type="PropertyFormulaExample.Shipper, PropertyFormulaExample" formula="dbo.GetShipper(shipvia)" />
    </class>
</hibernate-mapping>

实体:

public class Order
{
    public int OrderID { get; set; }
    public string CustomerID { get; set; }
    public Shipper ShipVia { get; set; }
}

public class Shipper : ILifecycle
{
    public int ShipperID { get; set; }
    public string CompanyName { get; set; }
    public string Phone { get; set; }
    #region ILifecycle Members
    public LifecycleVeto OnDelete(NHibernate.ISession s)
    {
        throw new NotImplementedException();
    }
    public void OnLoad(NHibernate.ISession s, object id)
    {
    }
    public LifecycleVeto OnSave(NHibernate.ISession s)
    {
        throw new NotImplementedException();
    }
    public LifecycleVeto OnUpdate(NHibernate.ISession s)
    {
        throw new NotImplementedException();
    }
    #endregion

}

最后是SQL函数:

CREATE FUNCTION dbo.GetShipper(@shipperId int)
RETURNS int
AS
BEGIN
RETURN @shipperId
END

显然,你会希望函数做一些有意义的事情,但想法是你为实体返回PK并实现ILifecycle。