Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've deleted the connection string from my web.config and Entity Framework is still connecting to the database! Where is the connection string being set? This is an issue because I need to make the live version of my website point to the live database.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
578 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's a gotcha I found with the "convention over configuration" philosophy when it comes to trying to connect to existing databases (like you're doing).

If your DbContext class (e.g. Northwind) is in a namespace (e.g. MvcProject), for some reason EF won't match the name of the class with a connection string in web.config named "Northwind" (or "MvcProject.Northwind"), and then it will just create a connection string defaulting to the local SQLEXPRESS instance, with a database called "MvcProject.Northwind". This will be an empty database. And you'll break your head trying to figure out why you're getting no data back, until you realize that you're not connected to the right DB.

The way I got around this (not elegant but it's the quickest way I found to fix it): add a constructor to your DbContext class that calls the base with the name of the connection string in web.config - e.g.

namespace MvcProject
{
    public class Northwind : DbContext
    {
        public Northwind() : base("Northwind") {}
    }
}

Hope that helps someone out there ;-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...