使用Code-First EntityFramework将ASP WebProject上传到WebHosting - CREATE DATABASE'master' [英] Upload ASP WebProject to WebHosting with Code-First EntityFramework - CREATE DATABASE 'master'
问题描述
所以我使用MVC构建我的asp.net web项目,它在localhost中使用EntityFramework 6.0的代码优先方法工作正常。
本周我买了一个新的网络托管上传我的网站。
问题是,每次运行网站时,都会尝试在数据库master中创建一个数据库,为什么会发生这种情况? / p>
我正在选择我的Web Hosting在我的ConnectionString上提供的正确的数据库。
有一个注释:I我也使用ASP Identity OWIN ...也许这是问题?它正在使用另一个ConnectionString?
我的身份配置(用于OWIN):
命名空间MyNamespace
{
public class IdentityConfig
{
public void Configuration(IAppBuilder app)
{
app .CreatePerOwinContext(()=> new MyContext());
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString(/ home / Login),
});
FormsAuthentication.SetAuthCookie(CookieValue,false);
}
}
}
这里是我的DbContext叫MyContext:
命名空间MyNamespace.DAL
{
public class MyContext:IdentityDbContext< IdentityUser>
{
public MyContext():base(MyNamespace.DAL.MyContext)
{
if(!Roles.Any(r => r.Name == admin)
{
var RoleManager = new RoleManager< IdentityRole>(new RoleStore< IdentityRole>(this));
RoleManager.Create(new IdentityRole(admin));
}
如果(!Users.Any(u => u.UserName ==myuser))
{
var store =新的UserStore< IdentityUser>(this);
var manager = new UserManager< IdentityUser>(store);
var user = new IdentityUser {UserName =myuser};
manager.Create(user,mypw123);
manager.AddToRole(user.Id,admin);
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove< PluralizingTableNameConvention>();
}
public DbSet< Item1> stuff1 {get;组; }
public DbSet< Item2> stuff2 {get;组; }
public DbSet< Item3> stuff3 {get;组; }
public DbSet< Item4> stuff4 {get;组; }
public DbSet< Item5> stuff5 {get;组; }
}
}
这是我的Web.Config:
<?xml version =1.0encoding =utf-8?>
< configuration>
< configSections>< / configSections>
< appSettings>
< add key =owin:AppStartupvalue =MyNamespace.IdentityConfig/>
< / appSettings>
< connectionStrings>
< add name =MyNamespace.DAL.MyContextproviderName =System.Data.SqlClientconnectionString =server = myhostingmssql07; uid = myuserid_en_wmx00; database = mydbname_en_wmx00; password = mybdpw; />
< / connectionStrings>
< system.web>
< compilation debug =truetargetFramework =4.5/>
< httpRuntime targetFramework =4.5/>
< customErrors mode =Off/>
< trust level =Full/>
< /system.web>
<! - 这里有更多的东西..-->
< / configuration>
PS:知道这个机制我用来创建默认的管理员并不是最好的方法,我稍后会把它改成种子方法,现在我只需要把这个工作,那么我将处理所有的重构。
PS2:导致错误的日志消息(我正在使用customErrors = Off,如上所示)以下行:
if(!Roles.Any(r => r.Name ==admin))
此行触发数据库master上的创建数据库,这不是ConnectionString上指定的!
应该在数据库上创建名为mydbname_en_wmx00的所有DbContext和IdentityDbContext表,如上面在ConnectionString中所见。
我尝试使用EntityFramework Default Factory在Web.Config上使用相同的ConnectionString参数值,我开始获取(Internal Server Error 500),所以我刚刚回滚并删除了EntityFramework Default Factory配置...
PS3:我知道如果我使用以下Initializer MyContext构造函数:
Database.SetInitializer< MyContext>(null);
它不会在数据库上触发任何CREATE,一切顺利,问题是我需要在数据库上手动设置一切,如AspNetRoles和AspNetUsers等,以及我所有的DbContext表(Stuff1,stuff2等)。
PS4:也许你在想这个链接是一个重复的问题,但它不是,他正在使用本地的SQLEXPRESS实例,我正在使用远程的mssql从我的付费主机...
非常感谢您的努力,您是否有机会知道这里发生了什么? EF Code-First自动生成数据库在付费网页托管上无效?
似乎这是一个问题从我的付费网络托管。
不支持代码优先的方法(包括从包管理器控制台运行更新迁移和种子方法),因为它总是参考我没有权限的主数据库,你可能会知道。
所以我想出了一个解决方法,我生成一个完整的SQL脚本从我的上下文和模型,然后我只是使用其系统中的工具在我的远程数据库服务器上运行SQL脚本,所有的表都是根据每个模型规范创建的。
要生成SQL脚本,我运行以下命令在包管理器控制台上(确保您键入启用迁移之前 - 如果您无法启用迁移,因为ConnectionString上的远程主机不允许,请创建一个新的ConnectionString指向本地数据库,然后再次运行启用迁移-Force 它将适用于我):
更新数据库 - 脚本 - SourceMigration:0
然后不要忘了告诉你的EF上下文,你使用的是一个null数据库初始化器它不会尝试使用代码优先方法删除/创建新的数据库:
Database.SetInitializer< YourContext>(null );
感谢StackOverFlow我发现这个解决方案,我们现在很幸运!
So I build my asp.net web project using MVC and it's working fine in localhost using code-first approach of EntityFramework 6.0.
This week I bought a new Web Hosting to upload my website.
The problem is that, everytime I run the website it tries to create a database in database 'master', why is this happening?
I am selecting the right database that my Web Hosting provided on my ConnectionString.
There is a note: I am also using ASP Identity OWIN... maybe that's the problem? it's using another ConnectionString ?
My Identity Config (Used for OWIN):
namespace MyNamespace
{
public class IdentityConfig
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new MyContext());
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Login"),
});
FormsAuthentication.SetAuthCookie("CookieValue", false);
}
}
}
And here is my DbContext called MyContext:
namespace MyNamespace.DAL
{
public class MyContext : IdentityDbContext<IdentityUser>
{
public MyContext() : base("MyNamespace.DAL.MyContext")
{
if (!Roles.Any(r => r.Name == "admin"))
{
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this));
RoleManager.Create(new IdentityRole("admin"));
}
if (!Users.Any(u => u.UserName == "myuser"))
{
var store = new UserStore<IdentityUser>(this);
var manager = new UserManager<IdentityUser>(store);
var user = new IdentityUser { UserName = "myuser" };
manager.Create(user, "mypw123");
manager.AddToRole(user.Id, "admin");
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<Item1> stuff1 { get; set; }
public DbSet<Item2> stuff2 { get; set; }
public DbSet<Item3> stuff3 { get; set; }
public DbSet<Item4> stuff4 { get; set; }
public DbSet<Item5> stuff5 { get; set; }
}
}
Here is my Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections></configSections>
<appSettings>
<add key="owin:AppStartup" value="MyNamespace.IdentityConfig" />
</appSettings>
<connectionStrings>
<add name="MyNamespace.DAL.MyContext" providerName="System.Data.SqlClient" connectionString="server=myhostingmssql07; uid=myuserid_en_wmx00; database=mydbname_en_wmx00; password=mybdpw;" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<customErrors mode="Off"/>
<trust level="Full" />
</system.web>
<!--More stuff here..-->
</configuration>
PS: I know that this mechanism I used to create default admins is not the best approach, I will change it to a seed method later, I just need to put this working right now, then I will handle all the refactoring.
PS2: The log message causing the error (I am using customErrors = Off as you can see above) is on the following line:
if (!Roles.Any(r => r.Name == "admin"))
This line triggers a create database on database 'master' , that's not what is specified on ConnectionString!!
It should create all the DbContext and IdentityDbContext tables on the Database called "mydbname_en_wmx00" as you can see above in ConnectionString..
I tried using EntityFramework Default Factory on Web.Config using as parameter value the same ConnectionString and I started getting (Internal Server Error 500), so I just rolled back and deleted this EntityFramework Default Factory configuration...
PS3: I know that if I use the following Initializer on MyContext constructor:
Database.SetInitializer<MyContext>(null);
it doesn't trigger any CREATE on Database and everything goes okay, the problem is that I need to set up everything manually on Database, like AspNetRoles and AspNetUsers, etc etc, and all my DbContext Tables (Stuff1, stuff2, etc).
PS4: Maybe you are thinking this link is a duplicate question, but it's not, he is using local SQLEXPRESS instance, and I am using a remote mssql from my paid host...
Thank you so much for your effort, do you know by any chance, what is happening here? EF Code-First auto-generate databases don't work on Paid-Web-Hostings??
It seems it's a problem from my paid web-hosting..
There isn't support for code-first approaches (that includes running Update Migrations and Seed Methods from Package Manager Console), because it always reference the 'master' Database which I don't have permissions, as you might know..
So I figured it out a workaround, I generate a full SQL Script from my Context and Models and then I just run the SQL Script on my Remote Database Server using a tool from their system, and all the tables are created according to each model specification.
To generate the SQL Script I run the following command on the Package Manager Console (make sure you typed Enable-Migrations before - if you can't Enable-Migrations because your remote host on the ConnectionString doesn't allow it, just create a new ConnectionString pointing to your local db and then run again "Enable-Migrations -Force" it will work, it did for me):
Update-Database -Script -SourceMigration:0
Then don't forget to tell your EF Contexts that you are using a null DatabaseInitializer so it doesn't try to drop/create a new Database using code-first approach:
Database.SetInitializer<YourContext>(null);
Thanks to StackOverFlow I found this solution, how lucky we are nowadays!
这篇关于使用Code-First EntityFramework将ASP WebProject上传到WebHosting - CREATE DATABASE'master'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!