简体   繁体   中英

How do I create a SQL Server Express database at runtime in a C# MVC App?

I'm trying to do this using Entity Framework 5 in C# in an MVC3 web application:

// Local DB connection
var dbId = String.Format(@"Data Source=.\SQLEXPRESS;AttachDbFilename={0}.mdf;Database=Tests;Integrated Security=True;Pooling=False;Connect Timeout=30;User Instance=True", _dbPath);
_connection = new SqlConnection(dbId);

Database.SetInitializer<MyContext>(new DropCreateDatabaseAlways<MyContext>());

// Reset database if the file exists
var ctx = new MyContext(_connection);
ctx.Database.CreateIfNotExists();
ctx.Database.Initialize(true);
ctx.SaveChanges();

return _connection;

This works for my tests, but not when I run the web application. When I run the web application, I get:

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)

I see in a few other questions people have suggested removing the 'User Instance' from the connection string, but that results in:

CREATE DATABASE permission denied in database 'master'.

Let me be entirely clear on my goal here: I'm trying to have the web application create database instances ( sqlexpress ) on demand.

Creating the database instances in advance is not a solution.

I'm quite puzzled about why some kind of special permission is needed when the app worker is the one accessing and creating the database.

How can you do this?

Using sqlite this is a trivial operation, and I'm starting to feel like using Entity Framework (and thus SQL Server Express) was mistake and I should have gone with fluent nhibernate and sqlite instead.

本文http://support.microsoft.com/kb/2002980建议这是“ ASP.Net V4.0”应用程序池“ ApplicationPoolIdentity”的默认帐户的文件权限问题,并建议将其更改为使用“网络服务”代替。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM