Create database using code first Entity Framework in SQL Server

entity-framework-6 sql-server-2014

Question

I am using code first EF and new to this framework. I am trying to create a database using Database.SetInitializer but it looks like I need SQL Server Express. But I have to create database in SQL Server 2014. How to do this?

Can anybody explain this with the example from EF-dbcontext book which has following classes.

 public class BreakAwayContext : DbContext
 {
    public DbSet<Destination> Destinations { get; set; }
    public DbSet<Lodging> Lodgings { get; set; }
    public DbSet<Trip> Trips { get; set; }
    public DbSet<Person> People { get; set; }
    public DbSet<Reservation> Reservations { get; set; }
    public DbSet<Payment> Payments { get; set; }
    public DbSet<Activity> Activities { get; set; }
}
class Program
{


static void Main(string[] args)
 {
  Database.SetInitializer(new InitializeBagaDatabaseWithSeedData());
  try
  {
      using (var context = new BreakAwayContext())
      {
          foreach (var destination in context.Destinations)
              Console.WriteLine(destination.Name);
      }
  }
    catch(Exception ex){

      Console.WriteLine(ex.ToString());
    }
  Console.Read();  
}
}

 public class InitializeBagaDatabaseWithSeedData : DropCreateDatabaseAlways<BreakAwayContext>
  {
    protected override void Seed(BreakAwayContext context)
    {
      context.Destinations.Add(new Destination
      {
        Name = "Hawaii",
        Country = "USA",
        Description = "Sunshine, beaches and fun."
      });

      context.Destinations.Add(new Destination
      {
        Name = "Wine Glass Bay",
        Country = "Australia",
        Description = "Picturesque sandy beaches."
      });
}
1
0
8/29/2015 8:38:17 AM

Accepted Answer

Set your connection string in your constructor:

public class BreakAwayContext : DbContext
{
    public BreakAwayContext()
        : base("MyConnectionString", throwIfV1Schema: false)
    {
    }
...

Then set your connection string in web.config or app.config:

<connectionStrings>
   <add name="MyConnectionString" connectionString="Data Source=servername;Initial Catalog=dbname;..." providerName="System.Data.SqlClient" />
</connectionStrings>
1
1/10/2019 8:15:22 AM


Related Questions





Related

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