EntityFramework代码优先迁移

时间:2013-01-16 19:08:23

标签: asp.net-mvc asp.net-mvc-4 migration entity-framework-5

我正在尝试使用Entityframework代码实现ASP.NET MVC 4应用程序。实际上我有2个数据上下文,一个自定义和默认的UsersContext。

namespace Namespace.Models
{
    public class StoreDB : DbContext
    {
        public DbSet<Supplier> Suppliers { get; set; }
        public DbSet<Vendor> Vendors { get; set; }
        public DbSet<Product> Products { get; set; }
    }
}

public class UsersContext : DbContext
{
    public UsersContext() : base("StoreDB")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
}

声明public UsersContext() : base("StoreDB")可能是错误的。但是当我离开默认值: base("DefaultConnection")时,创建了一个DefaultConnection数据库,当然,我只想要一个名为“StoreDB”的数据库。

我做了一些更改为属于UserProfile

UsersContext
[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime? DoB { get; set; }
}

我更新了Global.asax如下:

Database.SetInitializer(new Namespace.Models.StoreDbInitializer());
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Namespace.Models.UsersContext>());

但是当我运行应用程序时,我收到了这个错误:

CREATE DATABASE permission denied in database 'master'.

为什么要尝试在“master”下创建数据库?

我的连接字符串如下:

<add name="StoreDB" 
     connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=MyDB; Integrated Security=SSPI; MultipleActiveResultSets=True" 
     providerName="System.Data.SqlClient"/>

3 个答案:

答案 0 :(得分:1)

您是否在IIS中运行该网站?应用程序池是否在可以在SQL Express实例中创建数据库的帐户下运行?如果它以ApplicationPoolIdentity的形式运行,请尝试将其更改为NetworkService

另外,请尝试删除UsersContext并将该属性移至StoreDB上下文。您应该有一个与连接字符串同名的上下文

答案 1 :(得分:0)

听起来它忽略了这样一个事实:你有一个名为“StoreDB”的连接字符串,并且它正在尝试创建一个名为的数据库(这是你正在调用的相同构造函数的另一个函数)。

您可以明确告诉构造函数这是连接字符串的名称,如下所示:

public UsersContext() : base("name=StoreDB")
...

尝试一下,让我知道它是否有效。

答案 2 :(得分:0)

我认为问题在于我运行Visual Studio而不是管理员..我不知道为什么,但现在看来还可以。 很抱歉打扰你,谢谢你的时间和答案!

相关问题