Nhibernate连接Access的方法

方法一:

NHibernate连接Access的例子

NHibernate with Microsoft Access (Jet) Sample

This sample solution demonstrates NHibernate with Microsoft Access (Jet).  The code demonstrates:

  • How to configure NHibernate to use an Access (Jet) database.
  • How to disable aggressive connection closing to ensure you can use AutoNumber fields.
  • How to create a log file containing NHibernate debugging messages.

The sample is distributed as a Visual Studio 2005 solution with C#.  The sample requires NHibernate 1.2.0.CR1 (distributed separately).

Download

NHibernateWithAccess.zip 或者http://download.csdn.net/source/2445341(22kb)

Instructions

1. Download NHibernate

If you have not done so already, go to http://www.hibernate.org/6.html and look for the NHibernate binary release.  This sample was compiled against 1.2.0.CR1 (the latest version at the time this page was created).  The sample will be updated whenever NHibernate is updated.

2. Install NHibernate

The installer will suggest a default location of C:/Program Files/NHibernate.  You can select a different folder but make sure you remember the location.  You will need to browse to the folder after opening the sample solution (in order to correct the NHibernate references).  This is necessary because your computer is not likely to have the same folder structure as my computer.  :-)

3. Download Sample Solution

Download the sample solution and unzip to the location of your choice.  The solution should work from any folder.  If you have Microsoft Access, feel free to open the Sample.MDB database and look around.  It's nothing special.

4. Open Solution and Fix References

NHibernate is not distributed with this sample.  You will need to add references the NHibernate installation on your computer.  The solution will probably show some warning icons next to the references.

Fix the references to NHibernate.dll, NHibernate.JetDriver.dll and log4net.dll.  All three assemblies are located at <nhibernate-folder>/bin/net-2.0.  For example, if you installed NHibernate to the default folder, the assemblies will be located at C:/Program Files/NHibernate/bin/net-2.0

Example Results

The sample code will configure NHibernate to use Sample.mdb, then perform a few basic operations (e.g. saving a user, loading a user, and deleting a user) with all output sent to the console.   In the future I will add more complex operations but hopefully this will get you started.

Source Code Comments

If the sample works but you're still unable to get Jet to work with your real application, try the following:

  • Make sure your mapping files are marked as embedded resources (if you're loading mappings from an assembly).

  • Make sure your field names are not reserved by the Jet database engine.  For example, the word "Password" is reserved.  You must enclose reserved words in square brackets in your mapping files.  Look at User.xbm.xml for an example.

  • Make sure hibernate.cfg.xml is being copied to your output folder (if applicable).  You can instruct Visual Studio to copy this file to your output folder when rebuilding.

  • Make sure your connection string has the correct path to your MDB file.  You can use relative paths.  For example, if your database is located two folders above your executable folder, you can use a path like "../../MyData.mdb".

  • Make sure you're using the correct namespaces in your mapping and configuration files.

And please note: Access is not designed for server or enterprise applications.  It is a desktop database system.  You can reach the author at dave@thoughtproject.com for feedback or questions about this sample.

External Links

NHibernate
http://www.nhibernate.org

This is the official URL for the excellent NHibernate open source O/R system.

 

 

NHibernate Quick Start Guide
http://www.hibernate.org/362.html

A good starting point for learning NHibernate.

 

David Givoni's Blog
http://david.givoni.com/blog/

His blog has a number of useful postings about NHibernate.  This posting about reserved words in SQL saved me a lot of time.

 

SQL Reserved Words
http://sqlserver2000.databases.aspfaq.com/what-are-reserved-access-odbc-and-sql-server-keywords.html

 

Refer to this list if you get a syntax error with certain field names.  Reserved field names can be enclosed in [square brackets], e.g.:

<
property name="Password" column="[Password]" type="String" length="50"/>

方法二:

 官方没有提供链接access数据的专门的类,建议使用NHibernate.Dialect.SybaseDialect。它可以兼容对access数据库的操作。
方法:在app.config文件中配置如下信息:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="masparameter">
    <property name="dialect">NHibernate.Dialect.SybaseDialect</property>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.OleDbDriver</property>
    <property name="connection.connection_string">Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|/WorkPlatform.mdb</property>
    <property name="connection.isolation">ReadCommitted</property>   
    <!-- HBM Mapping Files -->
    <mapping assembly="wmadata" />
</session-factory>
</hibernate-configuration>

这样就完成了配置信息。

转载问题处理:

关于NHibernate如何连接Access,需要使用JetDriver,请参考这篇日志 NHibernate的ACCESS驱动----JetDriver

使用过程中会有一些问题,根据网友反馈,总结解决办法如下:

1、我下载你的包后自己替换了你net2.0下的东西。编译通过输出的NHibernate.JetDriver.Dll,引入到我的其他项目中还是不能用;单步时会出错,提示:Could not find the dialect in the configuration 请问这是什么问题,我始终找不到,按道理应该可以的啊。另外说明,我采用的是InPlaceConfigurationSource.如下:
IDictionary<string, string> properties = new System.Collections.Generic.Dictionary<string, string>();
properties.Add("hibernate.connection.driver_class", "NHibernate.JetDriver.JetDriver, NHibernate.JetDriver");
properties.Add("hibernate.dialect", "NHibernate.JetDriver.JetDialect,NHibernate.JetDriver");
properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider");
properties.Add("hibernate.show_sql", "false");
string strConn = GetFullDatabasePath(CORE_DB_PATH);
properties.Add("hibernate.connection.connection_string", strConn);
InPlaceConfigurationSource source = new InPlaceConfigurationSource();
source.Add(typeof(ActiveRecordBase), properties);
ActiveRecordStarter.Initialize(source, new Type[] {
typeof(MyClass)
});

----在最后的Initialize这里会出上面的错误

解决办法:把配置项里面的“hibernate.”去掉试试。
The configuration has changed since RC3 and you no longer need to prefix all keys with a hibernate. Things will break if you do. You’ll get a exception stating: Could not find the dialect in the configuration

2、Access中一个表A,有十个字段,其中有一个字段是Id(自动编号),我在用ActiveRecordBase的Save()方法后,再去Access中打开此表,发现数据都存进去了,但是我的代码中再以属性的方式(get,set)获取这个id,仍然是我初始定义的属性值0,也就是说Save()后,没有将这个自动编号的id值,返回给我。请问该如何处理?查看执行save的SQL,在C#中,我发现,只有两条语句,一个是NHibernate: insert into Table1(field1,field2) Values(?,?);@p1='XX',@p2='XX' 还有一个是NHibernate: select @@identity.
却没有NHibernate: Select 所有字段 where....查询刚刚插入的数据这条语句,所以导致我的实体类没有得到更新。

解决办法:After some research in the Hibernate documentation and on the Internet, I discovered that this is caused by the 'connection release mode'. The default connection release mode seems to release the connection after each SQL statement, so obviously, Access is not able to determine the correct ID of the last inserted record, since the __select @@identity command must be executed on the same connection as its related __insert statement. Now that we know what caused this problem, it is easy to fix it: just make sure that you do not use the default connection release mode when using NHibernate with MS Access. To do so, you should specify the connection release mode in your NHibernate configuration file like this: <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="hibernate.connection.release_mode">on_close</property> </session-factory></hibernate-configuration>

反馈补充:非常感谢你的回复。我的问题得以解决,按照上面的意思,在我的配置代码中添加properties.Add("connection.release_mode","on_close");既可。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值