Entity Framework Exception : “the underlying provider failed on open”

I came across this exception while calling a method in class library project (that in turns call a WCF service method), from another class library project. I have made use of the N-tier architecture that simply passes the objects of model classes to the other layers referencing their classes.

The exception ” the underlying provider failed on open”, occurred since my method inside the class library project, could not read the Connection string from the web.config in the service layer.

Let us now see a brief about how to solve the error:

1. Add a property, “ConnectionString” in the Model class (a class with collection of properties that is used for data transfer).

public class Model

// a class with collection of properties

.

public string ConnectionString {get;set;}

}

2. In the service layer, fetch the connection string and assign it to the model object’s ConnectionString property.

public void method(Model obj)

{

obj.ConnectionString = ConfigurationManager.ConnectionStrings[“connectionStringName”].ConnectionString;

Logic logicObj = new Logic(); //The class you are using the Data context of entity framework

logicObj.method(obj);

}

3. Now in the Class, where you make use of Entity framework, pass the connection string property as a parameter for data entity class’ constructor and write your logic.

public void method(Model obj)
{
using (DataEntities context = new DataEntities(obj.ConnectionString))
{
//your business logic goes here
.
.
context.AddToModel(obj);
context.SaveChanges();
}
}

Hope this implementation solves the issue! Happy coding!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s