[英]How to make Entity Framework Code First use the SQL Azure DB?
I'm start to learn EF now.我现在开始学习EF。 What I want to do is use EF code first create new tables in SQL Azure.
我想要做的是首先使用 EF 代码在 SQL Azure 中创建新表。
Here is my code:这是我的代码:
namespace WebApplication2
{
public class Blog
{
public int UserName { get; set; }
public int ID { get; set; }
}
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public BlogContext() : base("MYEF")
{
}
}
}
Code behind:后面的代码:
protected void Page_Load(object sender, EventArgs e)
{
using (var db = new BlogContext())
{
var blog = new Blog { UserName = 456 };
db.Blogs.Add(blog);
db.SaveChanges();
}
}
Web.config
: Web.config
:
<connectionStrings>
<add name="TestDBContext"
connectionString="Server=tcp:mydb.database.windows.net,1433;Database=MYEF;User ID=[Username];Password=[MyPassword];Trusted_Connection=False;Encrypt=True;PersistSecurityInfo=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
When I check my SQL Azure DB, no table has been created, EF still create the table MYEF
in the default SQL Server Express database.当我检查我的 SQL Azure DB 时,没有创建表,EF 仍然在默认的 SQL Server Express 数据库中创建表
MYEF
。
Has anyone done this successfully?有没有人成功地做到了这一点?
You should pass the connection string name to the base constructor of your BlogContext
like this您应该像这样将连接字符串名称传递给
BlogContext
的基本构造函数
public BlogContext()
: base("TestDBContext")
{
}
http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx
EntityFramework tries to infer the name of the ConnectionString in the web/app.config file from the name of the class which inherits DbContext. EntityFramework 尝试从继承 DbContext 的类的名称推断 web/app.config 文件中 ConnectionString 的名称。 In your case, this is BlogContext.
在您的情况下,这是 BlogContext。
If you simply changed如果你只是改变
<connectionStrings><add name="TestDBContext"
to到
<connectionStrings><add name="BlogContext"
then you could do public BlogContext()
without passing a hard string to the base class.那么你可以在不将硬字符串传递给基类的情况下执行
public BlogContext()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.