Microsoft Enterprise Library in Asp.Net

This asp.net tutorial, we will discuss how to use the Microsoft Enterprise Library in Asp.Net. We will see below Asp.Net enterprise library tutorials:

  • Insert data using inline sql statements using enterprise library in Asp.Net
  • Insert data using sql stored procedure using enterprise library in Asp.Net
  • Retrieve data from sql server using Microsoft enterprise library Asp.Net
  • Update record using Microsoft Enterprise library in Asp.Net
  • Delete record using Microsoft enterprise library in Asp.Net
  • Data access block of Microsoft enterprise library 6.0 using inline sql statement
  • Data access block of Microsoft enterprise library 6.0 using stored procedure
  • Download Microsoft Enterprise Library 6 developer guide free
  • Keyword not supported data source error in Asp.Net Enterprise Library
  • the type initializer for threw an exception enterprise library 6
  • Database provider factory not set for the static DatabaseFactory

Insert data using inline sql statements using enterprise library in Asp.Net

Now, we will see how to insert data into the database by using inline sql statements using enterprise library in Asp.Net.

To work with enterprise library first download Microsoft Enterprise Library 5.0.

We need to give reference in Bin folder to the following dlls:

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.DesignTime.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.EnterpriseLibrary.Data.SqlCe.dll
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll

Now open the web.config file to define the connection string. If you are using Windows authentication to login to database then write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;database=TestDB;Integrated Security=SSPI"/>
</connectionStrings>

But if you are using SQL Server authentication to login to SQL Server database then you can write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data
Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=aspdotnethelp;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>
</connectionStrings>

Below is the code:
.aspx code:

<form id="form1" runat="server">
<div>
Name:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
Age:
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox><br />
Location:
<asp:TextBox ID="txtLocation" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" /><br />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</div>
</form>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Configuration;

public partial class EnterpriseLibraryTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Database db = DatabaseFactory.CreateDatabase("connection");
string sql = "nsert into Employees (Name,Age,JoiningDate,Location) values (@Name,@Age,@JoiningDate,@Location)";
DbCommand dbCommand = db.GetSqlStringCommand(sql);
db.AddInParameter(dbCommand, "@Name", DbType.AnsiString, txtName.Text.ToString());
db.AddInParameter(dbCommand, "@Age", DbType.AnsiString, txtAge.Text.ToString());
db.AddInParameter(dbCommand, "@JoiningDate", DbType.DateTime, DateTime.Now);
db.AddInParameter(dbCommand, "@Location", DbType.AnsiString, txtLocation.Text.ToString());
try
{
int result = db.ExecuteNonQuery(dbCommand);
if (result > 0)
{
lblResult.Text = "Record saved successfully!";
}
else
{
lblResult.Text = "OOPS Some error occured!";
}
}
catch (Exception ex)
{
lblResult.Text = "OOPS Some error occured!";
}
}
}

Look at the using statements that we have used above. After that the data will be save in the database.

Insert data using sql stored procedure using enterprise library in Asp.Net

Now, we will see how to insert data using sql stored procedure using enterprise library in Asp.Net.

Now open the web.config file to define the connection string. If you are using Windows authentication to login to database then write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;database=TestDB;Integrated Security=SSPI"/>
</connectionStrings>

But if you are using SQL Server authentication to login to SQL Server database then you can write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data
Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=aspdotnethelp;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100″/>
</connectionStrings>

Below is the stored procedure:

USE [TestDB] GO

/****** Object: StoredProcedure [dbo].[Insert_Users] Script Date: 01/17/2013 22:05:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[Insert_Employees] @Name varchar(50),
@Age int,
@Location varchar(200)
AS
BEGIN
BEGIN TRANSACTION

BEGIN
INSERT INTO Employees (
Name,
Age,
JoiningDate,
Location
)
VALUES (
@Name,
@Age,
GETDATE(),
@Location)
END
IF @@ERROR = 0
BEGIN
COMMIT TRANSACTION
END
ELSE
BEGIN
ROLLBACK TRANSACTION
END
END

GO

Below is the code:

.aspx code:

<form id="form1″ runat="server">
<div>
Name:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
Age:
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox><br />
Location:
<asp:TextBox ID="txtLocation" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" /><br />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</div>
</form>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Configuration;

public partial class EnterpriseLibraryTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Database db = DatabaseFactory.CreateDatabase(“connection");
DbCommand dbCommand = db.GetStoredProcCommand(“Insert_Employees"); // Here Insert_Employees is the stored procedure name.
db.AddInParameter(dbCommand, “@Name", DbType.AnsiString, txtName.Text.ToString());
db.AddInParameter(dbCommand, “@Age", DbType.AnsiString, txtAge.Text.ToString());
db.AddInParameter(dbCommand, “@Location", DbType.AnsiString, txtLocation.Text.ToString());
try
{
int result = db.ExecuteNonQuery(dbCommand);
if (result > 0)
{
lblResult.Text = “Record saved successfully!";
}
else
{
lblResult.Text = “OOPS Some error occured!";
}
}
catch (Exception ex)
{
lblResult.Text = “OOPS Some error occured!";
}
}
}

Look at the using statements that we have used above. After that the data will be save in the database.

Retrieve data from sql server using Microsoft enterprise library Asp.Net

Now, we will see how to retrieve sql server table data and show in gridview using the Microsoft enterprise library.

Below is the stored procedure:

CREATE PROCEDURE Select_Employees

AS
BEGIN
Select * from Employees
END
GO

Below is the code:

.aspx code:

<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Configuration;

public partial class EnterpriseLibraryTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployees();
}
}
void BindEmployees()
{
Database db = DatabaseFactory.CreateDatabase(“connection");
DbCommand dbCommand = db.GetStoredProcCommand(“Select_Employees");

try
{
DataSet ds = db.ExecuteDataSet(dbCommand);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{

}
}
}

It will show records as shown in the figure below:

Microsoft Enterprise Library in Asp.Net

Update record using Microsoft Enterprise library in Asp.Net

Now, we will see how to update record using Microsoft Enterprise library in Asp.Net, how a user can update a record using enterprise library in Asp.Net.

In this post we will see, There will be one textbox where a user can put a ID and corresponding records will be showed in the corresponding textboxes. Then user can update the record and finally the data will be saved in the database.

Below is the code:

Stored Procedure:

Here are the two stored procedure used:

create procedure SelectEmployee
@Empid int
as
begin
Select * from EmloyeeDetail where [email protected]
end
go
ok

create procedure UpdateEmployeeData
@FirstName varchar(100),
@LastName varchar(100),
@Address varchar(100),
@ContactNo varchar(20),
@Empid int
as
begin
update EmloyeeDetail
set
[email protected],
[email protected],
[email protected],
[email protected]
where
[email protected]
end
go
ok

.aspx code:

<div>
<table>
<tr><td>Emp Id</td><td><asp:TextBox ID="txtId" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Button ID="btnEdit" runat="server" Text="Edit"
onclick="btnEdit_Click" />

</td></tr>
<tr><td>First Name</td><td><asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td></tr>
<tr><td>Last NAme</td><td><asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td></tr>
<tr><td>Address</td><td><asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td></tr>
<tr><td>Contact No</td><td><asp:TextBox ID="txtContactNo" runat="server"></asp:TextBox></td></tr>
<tr><td>
<asp:Button ID="btnUpdate" runat="server" Text="Update" onclick="btnUpdate_Click" /></td></tr>
</table>
</div>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common;
using System.Data;

public partial class SpSampleTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnEdit_Click(object sender, EventArgs e)
{
Database db = DatabaseFactory.CreateDatabase("connection");
DbCommand dbCommand = db.GetStoredProcCommand("[selectEmployee]");
db.AddInParameter(dbCommand, "@Empid", DbType.Int32, Convert.ToInt32(txtId.Text));
DataSet dataSet = db.ExecuteDataSet(dbCommand);
if (dataSet != null)
{
if (dataSet.Tables.Count >0)
{
txtFirstName.Text = dataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLastName.Text=dataSet.Tables[0].Rows[0]["LastName"].ToString();
txtAddress.Text = dataSet.Tables[0].Rows[0]["Address"].ToString();
txtContactNo.Text = dataSet.Tables[0].Rows[0]["ContactNo"].ToString();
}
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Database db = DatabaseFactory.CreateDatabase("connection");
DbCommand dbCommand = db.GetStoredProcCommand("[UpdateEmployeeData]");
db.AddInParameter(dbCommand, "@Empid", DbType.Int32, Convert.ToInt32(txtId.Text));
db.AddInParameter(dbCommand, "@FirstName", DbType.AnsiString, txtFirstName.Text);
db.AddInParameter(dbCommand, "@LastName", DbType.AnsiString, txtLastName.Text);
db.AddInParameter(dbCommand, "@Address", DbType.AnsiString, txtAddress.Text);
db.AddInParameter(dbCommand, "@ContactNo", DbType.AnsiString, txtContactNo.Text.ToString());
db.ExecuteNonQuery(dbCommand);
}
}

This is how we can update record using Microsoft enterprise library in Asp.Net.

Delete record using Microsoft enterprise library in Asp.Net

Now, we will see how to delete a record using Microsoft enterprise library in Asp.Net.

Now, we will see, whenever a user put an id in the textbox and click on submit, the data should get deleted from the database. Below is the full code:

Store Procedure:

CREATE PROCEDURE DeleteEmployeData
@Empid int
AS
BEGIN
DELETE FROM EmloyeeDetail WHERE [email protected]
END
GO

.aspx code:

<table>
<tr>
<td>
Emp Id
</td>
<td>
<asp:TextBox ID=”txtEmpid” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnDelete” runat=”server” Text=”Delete” OnClick=”btnDelete_Click” />
</td>
</tr>
<asp:Label ID=”lblResult” runat=”server” Text=”Label”></asp:Label>
</table>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common;
using System.Data;

public partial class DeleteData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnDelete_Click(object sender, EventArgs e)
{
Database db = DatabaseFactory.CreateDatabase(“connection”);
DbCommand dbCommand = db.GetStoredProcCommand(“[DeleteEmployeData]”);
db.AddInParameter(dbCommand, “@Empid”, DbType.Int32, Convert.ToInt32(txtEmpid.Text));

try
{
int result = db.ExecuteNonQuery(dbCommand);
if (result > 0)
{
lblResult.Text = “Record deleted successfully!”;
}
else
{
lblResult.Text = “Some error occured!”;
}
}
catch (Exception ex)
{
}
}
}

This is how we can delete record using Microsoft enterprise library in Asp.Net.

Data access block of Microsoft enterprise library 6.0 using inline sql statement

Now, we will see how to use data access block of Microsoft Enterprise Library 6.0.

First of all download Microsoft Enterprise Library 6.0 and after you can unzip for the required dlls.

The below dlls we needed to work with data access block”

  • Microsoft.Practices.EnterpriseLibrary.Common.dll
  • Microsoft.Practices.EnterpriseLibrary.Data.dll

Now open the web.config file to define the connection string. If you are using Windows authentication to log in to the database then write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;database=TestDB;Integrated Security=SSPI"/>
</connectionStrings>

But if you are using SQL Server authentication to login to SQL Server database then you can write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=aspdotnethelp;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100″/>
</connectionStrings>

Below is the full code:

protected void btnSubmit_Click(object sender, EventArgs e)
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create("connection");
string sql = "insert into Employees (Name,Age,JoiningDate,Location) values (@Name,@Age,@JoiningDate,@Location)";
DbCommand dbCommand = db.GetSqlStringCommand(sql);
db.AddInParameter(dbCommand, "@Name", DbType.AnsiString, txtName.Text.ToString());
db.AddInParameter(dbCommand, "@Age", DbType.AnsiString, txtAge.Text.ToString());
db.AddInParameter(dbCommand, "@JoiningDate", DbType.DateTime, DateTime.Now);
db.AddInParameter(dbCommand, "@Location", DbType.AnsiString, txtLocation.Text.ToString());
try
{
int result = db.ExecuteNonQuery(dbCommand);
if (result > 0)
{
lblResult.Text = "Record saved successfully!";
}
else
{
lblResult.Text = "OOPS Some error occured!";
}
}
catch (Exception ex)
{
lblResult.Text = "OOPS Some error occured!";
}
}

The above 2 lines which in bold are very important. Else you will get this error.

This is how we can use the data access block of Microsoft Enterprise Library 6.0.

Data access block of Microsoft enterprise library 6.0 using stored procedure

Let us discuss how to use data access block of Microsoft Enterprise Library 6.0 using a stored procedure.

Here check the stored procedure and the enterprise library code:

Stored Procedure:

USE [TestDB] GO

/****** Object: StoredProcedure [dbo].[Insert_Users] Script Date: 01/17/2013 22:05:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[Insert_Employees] @Name varchar(50),
@Age int,
@Location varchar(200)
AS
BEGIN
BEGIN TRANSACTION

BEGIN
INSERT INTO Employees (
Name,
Age,
JoiningDate,
Location
)
VALUES (
@Name,
@Age,
GETDATE(),
@Location)
END
IF @@ERROR = 0
BEGIN
COMMIT TRANSACTION
END
ELSE
BEGIN
ROLLBACK TRANSACTION
END
END

GO

Enterprise Library Code:

DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create("connection");
DbCommand dbCommand = db.GetStoredProcCommand("Insert_Employees"); // Here Insert_Employees is the stored procedure name.
dbCommand.CommandType = CommandType.StoredProcedure;
db.AddInParameter(dbCommand, "@Name", DbType.AnsiString, txtName.Text.ToString());
db.AddInParameter(dbCommand, "@Age", DbType.AnsiString, txtAge.Text.ToString());
db.AddInParameter(dbCommand, "@Location", DbType.AnsiString, txtLocation.Text.ToString());
try
{
int result = db.ExecuteNonQuery(dbCommand);
if (result > 0)
{
lblResult.Text = "Record saved successfully!";
}
else
{
lblResult.Text = "OOPS Some error occured!";
}
}
catch (Exception ex)
{
lblResult.Text = "OOPS Some error occured!";
}

This is how we can use the data access block of Microsoft enterprise library 6.0 using stored procedure.

Download Microsoft Enterprise Library 6 developer guide free

We can download Microsoft Enterprise Library 6 developer guide free from MSDN. The developer guide focus on below Application blocks:

  • Data Access Application Block
  • Exception Handling Application Block
  • Transient Fault Handling Application Block
  • Logging Application Block
  • Semantic Logging Application Block
  • Policy Injection Application Block
  • Validation Application Block.

Download Microsoft Enterprise Library 6 developer guide

Keyword not supported data source error in Asp.Net Enterprise Library

Now, we will see how to fix error Keyword not supported: ‘data source’. which comes while working in the Enterprise library.

I have put my connection string in web. a config like below:

<add name="MyConnection" providerName="System.Data.SqlClient" connectionString="Data  Source=WIN-PFCP2DGT8DI;database=LetUsDiscuss;Integrated Security=SSPI;"/>

But I was getting the below error:

Keyword not supported: ‘data source’.
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at Microsoft.Practices.EnterpriseLibrary.Data.Database.CreateConnection()
at Microsoft.Practices.EnterpriseLibrary.Data.Database.GetNewOpenConnection()
at Microsoft.Practices.EnterpriseLibrary.Data.Database.GetWrappedConnection()
at Microsoft.Practices.EnterpriseLibrary.Data.Database.GetOpenConnection()
at Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteNonQuery(DbCommand command)
at UserMaster.SignUp(String fullname, String emailid, String password) in e:\Bijaya\App_Code\UserMaster.cs:line 32

To fix the issue follow the below steps:

It was a silly mistake from my side. There were two spaces between the keyword Data and Source. When I remove one space, then it worked. Like below:

<add name="MyConnection" providerName="System.Data.SqlClient" connectionString="Data Source=WIN-PFCP2DGT8DI;database=LetUsDiscuss;Integrated Security=SSPI;"/>

This is how we can fix error Keyword not supported data source error in Asp.Net Enterprise Library.

the type initializer for threw an exception enterprise library 6

Recently while working with Enterprise Library 6, I face an error as “the type initializer for threw an exception” while creating a class object.

When I digg more into it, the actual error was like below:

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements.

{System.TypeInitializationException: The type initializer for ‘Class1’ threw an exception. —> System.InvalidOperationException: The static DatabaseFactory already has a database provider factory or custom methods set.
at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.SetDatabases(Func1 createDefaultDatabase, Func2 createNamedDatabase, Boolean throwIfSet)
at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.SetDatabaseProviderFactory(DatabaseProviderFactory factory, Boolean throwIfSet)
at …

If you are working with Enterprise library 6, then to work with data access block, then we need to write the below line within the static constructor.

static MyClass()
{
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
}

Else you will find the below error:

Database provider factory not set for the static DatabaseFactory

Actually, SetDatabaseProviderFactory method takes 2 parameters, and the second parameter takes either True or False. If you set it as false then it will not throw an exception if the factory is already set. Else it will throw an exception if the factory is already set.

So we need to modify the line like below so that once it sets next time it will not throw any exception.

static MyClass()
{
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(),false);
}

Database provider factory not set for the static DatabaseFactory

Now, we will see how to resolve the Microsoft enterprise library error which comes in version 6.

Full error message:

Database provider factory not set for the static DatabaseFactory. Set a provider factory invoking the DatabaseFactory.SetProviderFactory method or by specifying custom mappings by calling the DatabaseFactory.SetDatabases method.

Solutions:

If you are using Microsoft Enterprise Library 5.0 version, then while using application block you can write like below:

Database DB = DatabaseFactory.CreateDatabase("ConnectionString");

But in Microsoft Enterprise Library 6 you can not write like above because Enterprise library 6 requires to set for factory method.

SetDatabaseProviderFactory is a one-time setting before using the application block.

So we can write like this:

DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
SqlDatabase db = DatabaseFactory.CreateDatabase("ConnectionString") as SqlDatabase;

But the problem here is, SetDatabaseProviderFactory is a one time setting, so next time when this block executes it will give an expection like below:

“The static DatabaseFactory already has a database provider factory or custom methods set”

To avoid this exception, you can write below line inside a static constructor:

DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());

But the best approach according to me is instead of writting the above 2 lines, write like below:

DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create("ConnectionString");

Now exception will not be thrown.

You may like following Asp.Net tutorials:

This asp.net tutorial, we discussed how to work with Microsoft Enterprise Library in Asp.Net. Also, we saw below examples:

  • Insert data using inline sql statements using enterprise library in Asp.Net
  • Insert data using sql stored procedure using enterprise library in Asp.Net
  • Retrieve data from sql server using Microsoft enterprise library Asp.Net
  • Update record using Microsoft Enterprise library in Asp.Net
  • Delete record using Microsoft enterprise library in Asp.Net
  • Data access block of Microsoft enterprise library 6.0 using inline sql statement
  • Data access block of Microsoft enterprise library 6.0 using stored procedure
  • Download Microsoft Enterprise Library 6 developer guide free
  • Keyword not supported data source error in Asp.Net Enterprise Library
  • the type initializer for threw an exception enterprise library 6
  • Database provider factory not set for the static DatabaseFactory
Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>