如何在nhibernate中返回DataSet的值

时间:2011-08-09 11:25:19

标签: asp.net-mvc nhibernate c#-3.0

我正在使用以下代码

但是返回值

时出错
public DataSet GetImageGroupId(int CaseId)
    {
        NHibernate.ISessionFactory sessionfactory = NHibernateHelper.GetSessionFactory();
        NHibernate.ISession session = sessionfactory.OpenSession();

        StringBuilder queryBuilder = new StringBuilder();

        queryBuilder.Append(string.Format("SELECT Id,Name,ImageModalityId from ImageGroup where BaseCaseId='" + CaseId + "'"));

        IQuery query = session.CreateSQLQuery(queryBuilder.ToString()).AddEntity(typeof(ImageGroup));

        return // how to return a dataset.

    }

请帮帮我..

2 个答案:

答案 0 :(得分:2)

洛矶,

我认为你缺少Nhibernate的目的,NHibernate的想法是将你的数据库映射到你的域对象,所以像这样的类

public class ImageGroup
{
    public virtual int id { get; set; }
    public virtual String Name { get; set; }
    public virtual int ImageModalityId { get; set; }
    public virtual int BaseCaseId { get; set; }
}

然后,您可以在Nhibernate中使用映射文件来执行以下操作

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernateTest" assembly="NHibernateTest">
  <class name="ImageGroup" table="ImageGroup" lazy="false">
    <id name="id">
      <column name="id"/>
      <generator class="native"/>
    </id>
    <property name="Name">
      <column name="Name"/>
    </property>
    <property name="ImageModalityId">
      <column name="ImageModalityId"/>
    </property>
    <property name="BaseCaseId">
      <column name="BaseCaseId"/>
    </property>
  </class>
</hibernate-mapping>

并在像这样的方法中调用它

    public class Start
    {
         static ISessionFactory SessionFactory;

        public Start()
        {
            using (ISession session = OpenSession()) {

                {

                    ImageGroup imagegroup1 = session.Get<ImageGroup>(1);
                }

            }
    }
               static ISession OpenSession() {
            if (SessionFactory == null) //not threadsafe
                { //SessionFactories are expensive, create only once
                Configuration configuration = new Configuration();
                configuration.AddAssembly(Assembly.GetCallingAssembly());
                SessionFactory = configuration.BuildSessionFactory();
            }
            return SessionFactory.OpenSession();
        }
}

我引用此link

希望有所帮助

答案 1 :(得分:0)

NHibernate旨在为您提供强类型对象,而不是数据集/表。我建议将结果映射到一个对象,如果可能的话让nhibernate为你检索它们。如果你绝对需要一个数据集,你可以通过正常的ADO.net方式获得底层连接。

这样的东西应该对SQL Server起作用(使用SqlClient命名空间):

        using (var conn = session.Connection as SqlConnection)
        {
            conn.Open();
            var adapter = new SqlDataAdapter(string.Format("SELECT Id,Name,ImageModalityId from ImageGroup where BaseCaseId='{0}'", caseId), conn);
            var dataSet = new System.Data.DataSet();

            adapter.Fill(dataSet);

            return dataSet;
        }