Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Entity Framework Code First use the SQL Azure DB?

I'm start to learn EF now. What I want to do is use EF code first create new tables in 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:

<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.

Has anyone done this successfully?

like image 516
EthenHY Avatar asked Apr 29 '13 14:04

EthenHY


1 Answers

You should pass the connection string name to the base constructor of your BlogContext like this

public BlogContext()
    : base("TestDBContext")
{
}

http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx

like image 74
Pascal Avatar answered Sep 30 '22 16:09

Pascal