How to provide database configuration settings in code-first Entity Framework?

599 Views Asked by At

I am not using localdb or ./sqlexpress I have to use server name

MSOLDEV03\SQL2012

Here is my code for generating database; when I run I get a SqlConnection error "server not found":

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }

        public virtual List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }

        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }

I used command

 Enable-Migrations

this command makes migration folder but does not generate database on my SQL Server instance MSOLDEV03\SQL2012

Then I tried to run this code

  using (var db = new BloggingContext())
  {
            db.Blogs.Add(new Blog { Name = "Another Blog " });
            db.SaveChanges();

            foreach (var blog in db.Blogs)
            {
                Console.WriteLine(blog.Name);
            }
  }

  Console.WriteLine("Press any key to exit...");
  Console.ReadKey();

Still not generate database but gives error connection to SQL Server not found.

Here is my app.config file contains no sql connection

<entityFramework>
    <defaultConnectionFactory 
          type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="mssqllocaldb" />
        </parameters>
    </defaultConnectionFactory>
    <providers>
        <provider invariantName="System.Data.SqlClient" 
                  type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>
1

There are 1 best solutions below

6
On BEST ANSWER

In your context class constructor, you can give the key like:

public BloggingContext() : base("name=BloggingContextKey")
        {

        }

and then give this key a value in your configuration file:

<connectionStrings>
    <add name="BloggingContextKey" connectionString="Data Source=<Your server>; Initial Catalog=<Database>;user=<user>;pwd=<password>;" providerName="System.Data.SqlClient" />
  </connectionStrings>