3

我想从ASP.NET MVC项目中首先使用SQL Server CE 4的EF代码,但不是在App_Data文件夹中创建数据库,而是在我的工作站上安装的SQL Server Express实例中获得新数据库。安装SQL Server Express时,如何强制实体框架代码优先使用SQL Server CE?

如何获得在App_Data文件夹中创建的数据库?

web.config

<connectionStrings> 
    <add name="NerdDinners" connectionString="Data Source=|DataDirectory|NerdDinners.sdf" 
     providerName="System.Data.SqlServerCe.4.0"/> 
    </connectionStrings> 

Context类:

public class NerdDinners : DbContext 
{ 
    public DbSet<Dinner> Dinners { get; set; } 
    public DbSet<RSVP> RSVPs { get; set; } 
} 

编辑1
我想去阻止SQL Server Express的思维,可能迫使使用SQL Server CE的,但它导致了ProviderIncompatibleException,内部例外为

{"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"}

所以看来我的设置想要使用SQL Server Express。

编辑2 有人建议我在连接字符串名称,明确传递到的DbContext,所以我改变了我的上下文类以下几点:

public class NerdDinners : DbContext 
    { 
     public NerdDinners() : base("NerdDinners") { } 

     public DbSet<Dinner> Dinners { get; set; } 
     public DbSet<RSVP> RSVPs { get; set; } 
    } 

在DinnersController控制器,这是上下文如何实例化:

public class DinnersController : Controller 
    { 
     private NerdDinners db = new NerdDinners(); 

     // 
     // GET: /Dinners/ 

     public ViewResult Index() 
     { 
      return View(db.Dinners.ToList()); 
     } 

做出这些更改后,数据库仍在SQL Server Express中创建,因此看起来我的连接字符串被忽略。

+0

你有它配置如上,并没有得到sdf文件出现在斌/调试? – 2012-03-01 20:47:09

+0

@Adam Tuliper - 这是正确的。我在本地SQL Server Express实例中获得一个新的数据库。 – DaveB 2012-03-01 20:51:34

+0

没有其他连接字符串?还是安装了sqlce v 4? – 2012-03-01 20:53:27

回答

1

在ASP.NET MVC中有两个web.config文件。连接字符串需要在网站的根目录下,而不是在视图目录(我有我的地方)。一旦我把连接字符串放在项目根目录下的web.config中,我的SQL Server CE数据库就是先使用代码创建的,并且工作正常!

+0

did not甚至认为你会添加,因为它几乎配置什么只允许您的意见。这将解释为什么它不会找到它! :) – 2012-03-06 16:20:22

0

下载EFProfiler的试用版,查看是否可以看到连接字符串的名称。

确保遵守上述规则。如果你想给我一个样本项目,我会检查你的,但我的工作没有指定连接字符串和使用SQL CE。在上面的链接下载我的演示项目 - 是否有效?如果没有,我会质疑CE二进制文件。

您的上下文类是否在同一个项目中?是你的连接字符串命名为你的上下文类(它应该是)

换句话说,你的web.config你有NerdDinners,它的上下文类实际上命名为NerdDinners,如果不是它需要或改变id在连接字符串中。

相关问题