使用EF Code First的WPF MVVM

时间:2013-11-15 13:08:49

标签: c# sql-server-2008 entity-framework

运行我的WPF应用程序时没有创建数据库。我的代码出了什么问题:

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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我没有看到这里实例化的上下文。您必须创建上下文并尝试访问数据强制初始化:

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

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