2013-11-15 104 views
1

數據庫在運行我的WPF應用程序時未創建。這有什麼錯我的代碼:使用EF CodeFirst的WPF MVVM

enter image description here

的App.config

<connectionStrings> 
    <add name="JanathaPOSConn" 
    connectionString="Server=.\SQLEXPRESS;Database=JanathaDb;Trusted_Connection=true" 
    providerName="System.Data.SqlClient" /> 
    </connectionStrings> 

POCO類1:

namespace JanathaPOS.Model 
{ 
    [Table("UserRoles")] 
    public class UserRole 
    { 
     [Key] 
     public string Id { get; set; } 
     [MaxLength(50)] 
     public string Name { get; set; } 
     [MaxLength(50)] 
     public string Description { get; set; } 
    } 
} 

POCO類2:

namespace JanathaPOS.Model 
{ 
    [Table("Users")] 
    public class User 
    { 
     [Key] 
     public string Id { get; set; } 
     [MaxLength(50)] 
     public string Name { get; set; } 
    } 
} 

上下文類:

namespace JanathaPOS.Model 
{ 
    /// <summary> 
    /// 
    /// </summary> 
    class JanathaPosDbContext : DbContext 
    { 
     private static JanathaPosDbContext _context; 

     /// <summary> 
     /// 
     /// </summary> 
     /// <returns></returns> 
     public static JanathaPosDbContext GetContext() 
     { 
      if (_context == null) 
      { 
       _context = new JanathaPosDbContext(); 
      } 
      return _context; 
     } 

     /// <summary> 
     /// 
     /// </summary> 
     public JanathaPosDbContext() : base("JanathaPOSConn") { } 

     /// <summary> 
     /// 
     /// </summary> 
     /// <param name="modelBuilder"></param> 
     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Entity<UserRole>(); 
      modelBuilder.Entity<User>(); 

      base.OnModelCreating(modelBuilder); 
     } 

     public DbSet<UserRole> UserRoles { get; set; } 
     public DbSet<User> Users { get; set; } 

    } 
} 

XAML:

namespace JanathaPOS 
{ 
    /// <summary> 
    /// Interaction logic for App.xaml 
    /// </summary> 
    public partial class App : Application 
    { 
     protected override void OnStartup(StartupEventArgs e) 
     { 
      Database.SetInitializer(new DropCreateDatabaseIfModelChanges<JanathaPosDbContext>()); 

      base.OnStartup(e); 
     } 
    } 
} 
+0

您是收到錯誤或異常?它是什麼?您可能不希望在應用程序的生命週期中擁有單一的上下文。 – Steve

+0

獲取沒有錯誤,沒有例外,但沒有創建數據庫。 – Jobi

+0

對不起!我是WPF的初學者。你能解釋一下嗎? – Jobi

回答

1

我看不出這裏實例化的背景下。你必須創建上下文,並試圖訪問數據強制初始化:

using (var ctx = new JanathaPosDbContext()) 
{ 
    // access the data 
    var roles = ctx.UserRoles.ToList();   

    // or force the initialization 
    ctx.Database.Initialize(true); 
} 
+0

現在它正在工作......謝謝 – Jobi