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

azure azure-sql-database c# ef-code-first entity-framework


I've just started learning EF. I want to build new tables in SQL Azure using EF code initially.

This 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 used:

 protected void Page_Load(object sender, EventArgs e)
        using (var db = new BlogContext())
            var blog = new Blog { UserName = 456 };

Web.config :

    <add name="TestDBContext" 
         connectionString=",1433;Database=MYEF;User ID=[Username];Password=[MyPassword];Trusted_Connection=False;Encrypt=True;PersistSecurityInfo=True" 
         providerName="System.Data.SqlClient" />

No table has been generated when I check my SQL Azure DB, however EF still creates the table.MYEF in the SQL Server Express database by default.

Has anyone attempted this and succeeded?

11/28/2014 9:50:03 PM

Accepted Answer

The connection string name should be provided to the base constructor of yourBlogContext like as

public BlogContext()
    : base("TestDBContext")

4/29/2013 5:24:47 PM

Popular Answer

The name of the class that inherits DbContext is used by EntityFramework to determine the name of the ConnectionString in the web/app.config file. This is BlogContext in your situation.

If you just made a change

<connectionStrings><add name="TestDBContext"


<connectionStrings><add name="BlogContext" 

after which you couldpublic BlogContext() without giving the base class a hard string.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow