1

我搜索范围广泛,通过教程和技巧,但它只是不会工作!ASP.NET EF5代码优先不创建SQL Server CE数据库

EF 5代码优先不生成我的SQL Server CE 4数据库文件。

我有一个ASP.NET Web应用程序,我想通过使用代码优先的方法生成数据库。

这里是我的模型类:

public class Class 
    { 
     [Key] 
     public int id { get; set; } 
     public bool isLecture { get; set; } 

     public int courseId { get; set; } 
     public virtual Course course { get; set; } 
     public int teacherId { get; set; } 
     public virtual Teacher teacher { get; set; } 
    } 

    public class Course 
    { 
     [Key] 
     public int id { get; set; } 
     public string name { get; set; } 
     public int semester { get; set; } 
    } 

    public class Teacher 
    { 
     public int id { get; set; } 
     public string name { get; set; } 
     public string lastName { get; set; } 
    } 

这里是上下文:

public class MyContext : DbContext 
    { 
     public DbSet<Class> Classes { get; set; } 
     public DbSet<Teacher> Teachers { get; set; } 
     public DbSet<Course> Courses { get; set; } 
    } 

这里是web.config连接字符串:

<add name="MyContext" 
     connectionString="Data Source=|DataDirectory|\MyContext.sdf" 
     providerName="System.Data.SqlServerCe.4.0" /> 

这是global.asax.cs

protected void Application_Start() 
    { 
     Database.SetInitializer<MyContext> 
      (new DropCreateDatabaseIfModelChanges<MyContext>()); 

     ... 
    } 

我试过w /和w/o这些行global.asax.cs和W /和无连接字符串。

应用程序加载和工作,但数据库文件只是没有创建。我试图自己创建.sdf文件,所以它可以由EF代码填充,但它仍然是空的。

该项目是ASP.NET MVC 4 HotTowel模板所做的,如果这意味着什么,我使用Visual Studio 2012

解决:

需要该代码在global.asax.cs

MyContext context = new MyContext(); 
    context.Database.Initialize(true); 

回答

0

这对我的作品 - 你需要连接工厂...

<configSections>... 
</configSections> 
<entityFramework> 
    <defaultConnectionFactory 
     type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework"> 
     <parameters> 
      <parameter value="System.Data.SqlServerCe.4.0" /> 
     </parameters> 
    </defaultConnectionFactory> 
</entityFramework> 
+0

仍然没有数据库文件。在数据连接下,服务器资源管理器与MyContex.sdf的链接已断开,当我尝试打开它时,它会显示: '找不到数据库文件。检查数据库的路径。 [数据源= c:\ ...路径... \ MyProject \ SekretarskiModul \ App_Data \ MyContext.sdf]' – Sljux 2013-04-25 14:51:17

相关问题