Entity database connection error

First I am using Entity framework (first code). I 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 my application in debug mode, I get the following exception in this expression.

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 retrieving provider information from the database. It could be caused by Entity Framework using the wrong connection string. Check for internal exceptions and check if 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; }

 }

      

+3


source to share


1 answer


Your web.config declares a connection string named "ContactMgrDBContext", while your context class refers to the connection string name "DBConnectionString".

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

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

      



It also seems like you are trying to use localdb to work with your database. I tried working with your name Data Source=(Local)

and got similar errors. You can try updating it to use Data Source=(localdb)\v11.0

like this:

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

      

+3


source







All Articles