我首先使用代码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."
});
}
答案 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>