Database is not creating while running my WPF application. What's wrong with my code:
App.config
<connectionStrings>
<add name="JanathaPOSConn"
connectionString="Server=.\SQLEXPRESS;Database=JanathaDb;Trusted_Connection=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
POCO class 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 class 2 :
namespace JanathaPOS.Model
{
[Table("Users")]
public class User
{
[Key]
public string Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
}
}
Context class :
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);
}
}
}
I don't see the context instantiated here. You have to create the context and try to access the data or force the initialization:
using ( var ctx = new JanathaPosDbContext() )
{
// access the data
var roles = ctx.UserRoles.ToList();
// or force the initialization
ctx.Database.Initialize( true );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.