1

I have a local ASP.NET MVC 3 Windows Azure Project where I use a local instance of MSSQL Express for my emulator.

In my web.config I have the following connection string:

<add name="ExampleDb" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ExampleDb;User Instance=true;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

For debugging purposes I have the following in my WebRole.cs file:

public override bool OnStart() 
{
    ExampleDb context = new ExampleDb();
    context.ExampleItemEntries.Add(new ExampleItem() { ExampleItemId = 1, Att1 = "1", Att2 = "2" });
    context.SaveChanges();     
    return base.OnStart();
}

When I perform this action I can actually see the content in my code-first generated database (using Entity Framework). Database: ExampleDb, Table: ExampleItem.

However, doing the exact same thing in ExampleController does NOT update the database. Instead this data goes somewhere else (I have no idea where). When I visit my controller via the browser I can upload data and look at it but it is not stored in my ExampleDb database, only data sent from WebRole.cs is in the database.

Any ideas what's causing this behaviour?

ExampleDb.cs looks like this:

public class ExampleDb : DbContext
{
    public ExampleDb() : base("ExampleDb") { }
    public DbSet<ExampleItem> ExampleItemEntries { get; set; }     
}
4

2 回答 2

2

您的连接字符串包含“用户实例=真”。这意味着 SQLEXPRESS 使用用户实例来存储您的数据。这是包含一组新数据库的完全不同的 SQL Server 实例。

我假设 WebRole.cs 中的代码与 ExampleController 中的代码在不同的用户帐户中运行。当 ExampleController 在非管理员用户帐户下运行时,将使用用户实例...

因此,当您从连接字符串中删除 'User Instance=True' 并为 SQLEXPRESS 数据库实例分配适当的访问权限时,即可解决问题。

于 2012-06-07T16:06:55.643 回答
0

在 CodeFirst 模型中,您应该首先在 web.config 中定义连接字符串,如下所示:

<connectionStrings>
 <add name="ExampleDbConnection"
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
                   database=ExampleDb;
                   AttachDBFilename=|YouDataDirectory|yourdb.mdf;
                   User Instance=true"
       providerName="System.Data.SqlClient" />
<connectionStrings/>

DbContext 类构造函数接受在 web.config 中指定连接字符串名称的名称-值对。因此,您可以在上下文中引用此连接字符串:

class ExampleDb : DbContext
{
  public ExampleDb() : base("name=ExampleDbConnection") { }
  ...
}

此代码在 ASP.NET MVC Web 角色中运行良好,因此您可以按上述方式尝试。

于 2012-06-08T02:24:34.450 回答