CodeFirst使用EntityFramework不在sql server Management中创建数据库

时间:2016-03-17 09:54:29

标签: c# sql-server entity-framework-6

我是Entityframework的新手。我正在尝试使用entityFramework的Codefirst方法创建数据库。我的代码在这里:

public class AppointmentInfo
{
   public AppointmentInfo()
   { }
   public Guid UniqueId { get; set; }
   public string Subject { get; set; }
   public DateTime StartDate { get; set; }
   public DateTime StartTime { get; set; }
   public DateTime EndDate { get; set; }
   public DateTime EndTime { get; set; }
   [ForeignKey="UniqueId "]
   public Client client { get; set; }

   public string Chargeable { get; set; }
   public string Activity { get; set; }
   public string DetailText { get; set; }
   public string Employee { get; set; }
}


public class Client
{
    public Guid UniqueId { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get;set;}
}

public class AppointmentsDbContext : DbContext
{
    public AppointmentsDbContext()
        : base("AppointmentConnectionString")
    {

    }
    public DbSet<AppointmentInfo> AppointmentInfos { get; set; }
    public DbSet<Client> clients { get; set; }
}

这是我在app.config中定义我的connectionstring的方式:

<connectionStrings>
<add name="AppointmentConnectionString" 
connectionString="Server=DHRUV;Database=Client_Appointments;Integrated Security=true" 
providerName="System.Data.SqlClient"/>
</connectionStrings>

这不会在Sql server management中创建数据库。我忘了实现什么?如何创建数据库? 请帮忙!

2 个答案:

答案 0 :(得分:0)

虽然EF代码首先应该在第一次运行应用程序时创建数据库。尝试在DbContext中设置它:

Database.SetInitializer<MyDBContext>(new CreateDatabaseIfNotExists<MyDBContext>());

http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx

答案 1 :(得分:0)

EntityFramework不会为您创建数据库'DHRUV',您必须创建它并将您的帐户添加到其安全表中。然后,EF将显示数据库的当前状态并执行挂起的迁移。