运行我的WPF应用程序时没有创建数据库。我的代码出了什么问题:
的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 :(得分:1)
我没有看到这里实例化的上下文。您必须创建上下文并尝试访问数据或强制初始化:
using ( var ctx = new JanathaPosDbContext() )
{
// access the data
var roles = ctx.UserRoles.ToList();
// or force the initialization
ctx.Database.Initialize( true );
}