使用SQL Server中的代码首先使用Entity Framework创建数据库

时间:2015-08-28 15:39:18

标签: entity-framework-6 sql-server-2014

我首先使用代码EF和此框架的新功能。我正在尝试使用Database.SetInitializer创建数据库,但看起来我需要SQL Server Express。但我必须在SQL Server 2014中创建数据库。如何做到这一点?

任何人都可以使用EF-dbcontext book中的示例解释这一点,该书包含以下类。

 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 :(得分:1)

在构造函数中设置连接字符串:

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

然后在web.config或app.config中设置连接字符串:

<connectionStrings>
   <add name="MyConnectionString" connectionString="Data Source=servername;Initial Catalog=dbname;..." providerName="System.Data.SqlClient" />
</connectionStrings>