raring sunny
raring sunny

Reputation: 191

Entity framework database connection error

I am using the Entity framework (code first) first time. I have created a context class with the following code.

public class ContactContext : DbContext
{
    public ContactContext()
        : base("DBConnectionString")
    {
        Database.SetInitializer<ContactContext>(new DropCreateDatabaseIfModelChanges<ContactContext>());
    }

    public DbSet<Contact> Contacts { get; set; }

}

Web.config file:

<add name="ContactMgrDBContext" connectionString="Data Source=(Local);Initial Catalog=ContactsDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>

Controller class:

public class ContactController : Controller
{

    ContactContext db = new ContactContext();

// // GET: /Contact/

    public JsonResult ContactList(int? selectedContact)
    {

        IQueryable<Contact> contacts = db.Contacts;

        //contacts.ToList()

        var contactsJson = JsonConvert.SerializeObject(contacts.ToList());

        return Json(contactsJson, JsonRequestBehavior.AllowGet);

}

When I run the application in debug mode, I get the following exception at this statement.

var contactsJson = JsonConvert.SerializeObject(contacts.ToList());

An exception of type 'System.Data.ProviderIncompatibleException' occurred in EntityFramework.dll but was not handled in user code Additional information: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

Contact class code:

public class Contact
 {
    [Key]
    public int ContactId { get; set; }
    [Required, MaxLength(100)]
    public string FirstName { get; set; }
    [Required, MaxLength(100)]
    public string LastName { get; set; }
    public string EMail { get; set; }
    public string Phone { get; set; }
    public string BusinessName { get; set; }

 }

Upvotes: 3

Views: 19381

Answers (1)

cmcquillan
cmcquillan

Reputation: 726

Your web.config declares a connection string of name "ContactMgrDBContext" while your context class references a connection string name "DBConnectionString".

Try updating your context class constructor to use the correct name and syntax:

public ContactContext()
    : base("name=ContactMgrDBContext")
{
    Database.SetInitializer<ContactContext>(new DropCreateDatabaseIfModelChanges<ContactContext>());
}

It also appears that you are trying to use localdb to work on your database. I tried running with your Data Source=(Local) name and got similar errors. You may want to try updating it to use the Data Source=(localdb)\v11.0 like so:

<add name="ContactMgrDBContext" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ContactsDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>

Upvotes: 3

Related Questions