1
數據庫在運行我的WPF應用程序時未創建。這有什麼錯我的代碼:使用EF CodeFirst的WPF MVVM
的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);
}
}
}
您是收到錯誤或異常?它是什麼?您可能不希望在應用程序的生命週期中擁有單一的上下文。 – Steve
獲取沒有錯誤,沒有例外,但沒有創建數據庫。 – Jobi
對不起!我是WPF的初學者。你能解釋一下嗎? – Jobi