FluentData入门(二)--创建DbContext

by kevin 7. 九月 2013 13:58 >

如何创建和初始化一个DbContext
可以在*.config文件中配置connection string,将connection string name或者将整个connection string 作为参数传递给DbContext来创建DbContext。

重要配置
IgnoreIfAutoMapFails – IDbContext.IgnoreIfAutoMapFails返回一个IDbContext,该实例中,如果自动映射失败时是否抛出异常

通过*.config中配置的ConnectionStringName创建一个DbContext

   1: public IDbContext Context()
   2: {
   3:     return new DbContext().ConnectionStringName("MyDatabase",
   4:             new SqlServerProvider());
   5: }

 

调用DbContext的ConnectionString方法显示设置connection string来创建
 

   1: public IDbContext Context()
   2: {
   3:     return new DbContext().ConnectionString(
   4:     "Server=MyServerAddress;Database=MyDatabase;Trusted_Connection=True;", new SqlServerProvider());
   5: }

其他可以使用的Provider

只有通过使用不同的Provider,就可以切换到不同类型的数据库服务器上,比如
AccessProvider, DB2Provider, OracleProvider, MySqlProvider, PostgreSqlProvider, SqliteProvider, SqlServerCompact, SqlAzureProvider, SqlServerProvider.

 

Create and initialize a DbContext
The connection string on the DbContext class can be initialized either by giving the connection string name in the *.config file or by sending in the entire connection string.

Important configurations
IgnoreIfAutoMapFails - Calling this prevents automapper from throwing an exception if a column cannot be mapped to a corresponding property due to a name mismatch.

Create and initialize a DbContext
The DbContext can be initialized by either calling ConnectionStringName which will read the connection string from the *.config file:
public IDbContext Context()
{
    return new DbContext().ConnectionStringName("MyDatabase",
            new SqlServerProvider());
}

or by calling the ConnectionString method to set the connection string explicitly:
public IDbContext Context()
{
    return new DbContext().ConnectionString(
    "Server=MyServerAddress;Database=MyDatabase;Trusted_Connection=True;", new SqlServerProvider());
}

Providers
If you want to work against another database than SqlServer then simply replace the new SqlServerProvider() in the sample code above with any of the following:
AccessProvider, DB2Provider, OracleProvider, MySqlProvider, PostgreSqlProvider, SqliteProvider, SqlServerCompact, SqlAzureProvider, SqlServerProvider.

分享到: 更多