как я могу исправить NHibernate.Cfg.HibernateConfigException - PullRequest
0 голосов
/ 16 октября 2019

Я обнаружил ошибку при создании примера применения nebernate, но я не знаю, в чем проблема. Посмотрите на код здесь и найдите часть, которую вы хотите изменить.

  • моя база данных - mysql, и я изменил свойства cfg.xml, him.xml
  • ошибка: NHibernate.Cfg.HibernateConfigException: 'Произошло исключение при разборе конфигурации

MainWindow.cs

      private void GetStudent()
    {
        System.Collections.IList siteList;
        ISessionFactory factory =
        new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory();

        using (ISession session = factory.OpenSession())
        {
            ICriteria sc = session.CreateCriteria(typeof(Student));
            siteList = sc.List();
            session.Close();
        }
        factory.Close();

        datagrid.ItemsSource = siteList;
    }

Stduent.cs

 public class Student
{
    private int grade;
    private int cclass;
    private string name;
    private int no;
    private string score;
    public virtual int Grade { 
        get { return grade; }
        set { grade = value; }
    }
    public virtual int Cclass
    {
        get { return cclass; }
        set { cclass = value; }
    }
    public virtual string Name
    {
        get { return name; }
        set { name = value; }
    }
    public virtual int No
    {
        get { return no; }
        set { no = value; }
    }

    public virtual string Score
    {
        get { return score; }
        set { score = value; }
    }
    public Student()
    {

    }
}

Student.hbm.xml

    <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="WpfStudent.Student" dynamic-insert="true" dynamic-update="true" table="student">
    <id name="No" column="no" type="int">
      <generator class="increment"></generator>
    </id>
    <property name="Grade" column="grade" type="int"></property>
    <property name="Cclass" column="cclass" type="int"></property>
    <property name="Name" column="name" type="String"></property>
    <property name="Score" column="score" type="String"></property>
  </class>
</hibernate-mapping>

hibernate.cfg.xml

  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

  <!-- an ISessionFactory instance -->
  <session-factory>

    <!-- properties -->
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
    <property name="connection.connection_string">server=localhost;user id=root;persistsecurityinfo=True;database=student;allowuservariables=True</property>
  <property name="dialect">NHibernate.Dialect.MySQL55InnoDBDialect</property>

    <!-- mapping files -->
    <mapping resource="WpfStudent.Student.hbm.xml" assembly="WpfStudent" />
  </session-factory>

</hibernate-configuration>

MainWindow.xaml

<Window x:Class="WpfStudent.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfStudent"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <DockPanel LastChildFill="False">
        <Border DockPanel.Dock="Left" Width="610"  Padding="10">
            <DataGrid Width="590" Height="400" HorizontalAlignment="Left" Name="studentDataGrid" ColumnWidth="*" AutoGenerateColumns="False" >
                <DataGrid.Columns>
                    <DataGridTextColumn Header="grade" Binding="{Binding grade,NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>
                    <DataGridTextColumn Header="class" Binding="{Binding cclass, NotifyOnTargetUpdated=True,UpdateSourceTrigger=PropertyChanged}" Foreground="Black"/>
                    <DataGridTextColumn Header="name" Binding="{Binding name, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>
                    <DataGridTextColumn Header="no" Binding="{Binding no, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>
                    <DataGridTextColumn Header="score" Binding="{Binding score, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>

                </DataGrid.Columns>
            </DataGrid>
        </Border>
        <Border DockPanel.Dock="Right" Width="180"  Padding="0">
            <Grid >
                <Grid.RowDefinitions>
                    <RowDefinition Height="25*"/>
                    <RowDefinition Height="25*"/>
                    <RowDefinition Height="25*"/>
                    <RowDefinition Height="25*"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="15*"/>
                    <ColumnDefinition Width="35*"/>
                    <ColumnDefinition Width="15*"/>
                </Grid.ColumnDefinitions>
                <Button x:Name="ReadBtn" Content="READ" VerticalAlignment="Center" Height="25" Margin="10,15,10,15"  Grid.Row="0" Grid.Column="1" Click="ReadBtn_Click"/>
                <Button x:Name="InsertBtn" Content="INSERT" VerticalAlignment="Center" Height="25" Margin="10"  Grid.Row="1" Grid.Column="1" Click="InsertBtn_Click"/>
                <Button x:Name="UpdateBtn" Content="UPDATE" VerticalAlignment="Center" Height="25" Margin="10"  Grid.Row="2" Grid.Column="1" Click="UpdateBtn_Click"/>
                <Button x:Name="DeleteBtn" Content="DELETE" VerticalAlignment="Center" Height="25" Margin="10"  Grid.Row="3" Grid.Column="1" Click="DeleteBtn_Click" />
            </Grid>
        </Border>


    </DockPanel>
</Window>

Ответы [ 2 ]

0 голосов
/ 17 октября 2019

Поскольку ваша база данных MySql , вам, вероятно, следует использовать

<property name="connection.driver_class">
  NHibernate.Driver.MySqlDataDriver
</property>
<property name="dialect">
  NHibernate.Dialect.MySQL55InnoDBDialect
</property>

См. документацию Таблица 3.3. NHibernate SQL Диалекты для возможных диалектов для MySql. Также Data Source= в вашем connection.connection_string выглядит странно для меня. Я бы удалил эту строку.

Если это еще не сделано, вам нужно установить и ссылаться на пакет Nuget MySql.Data в своем проекте.

0 голосов
/ 17 октября 2019

Имеется лишний пробел в атрибуте name * value (последняя позиция) . Вместо этого:

<property name ="connection.provider ">...
<property name ="dialect ">...
<property name ="connection.driver_class ">...
<property name ="connection.connection_string ">..

нам нужно следующее:

<property name ="connection.provider">...
<property name ="dialect">...
<property name ="connection.driver_class">...
<property name ="connection.connection_string">..

ПРИМЕЧАНИЕ: также в VS добавьте XML-схему в игру "nhibernate-configuration.xsd" и дляфайлы сопоставления "nhibernate-mapping.xsd" ... которые выявят множество проблем еще до компиляции

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...