的EntityFramework - 哪里是连接字符串? [英] EntityFramework - Where is the connection string?

查看:279
本文介绍了的EntityFramework - 哪里是连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从我的web.config中删除的连接字符串和实体框架仍然连接到数据库!哪里是连接字符串被设置?这是一个问题,因为我需要让我的网站点的真人版到实时数据库中。

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.

推荐答案

下面是一个疑难杂症,我发现用约定优于配置的理念,当谈到试图连接到现有的数据库(如你正在做的)。

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).

如果您的DbContext类(如罗斯文)是一个命名空间(如MvcProject),由于某种原因,EF不会在类的名称,在web.config中的连接字符串名为Northwind(或MvcProject匹配。罗斯文),然后将它只需创建一个连接字符串默认为本地SQLEX $ p $干燥综合征例如,一个叫做数据库MvcProject.Northwind。这将是一个空数据库。你会打破你的头想,为什么你没有得到数据传回,直到你意识到你没有连接到正确的DB弄清楚。

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.

我身边有这样的方式(而不是优雅,但它是我找到解决它的最快方法):添加一个构造函数调用与web.config中的连接字符串的名称基地您的DbContext类 - 例如

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 ;-)

这篇关于的EntityFramework - 哪里是连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆