简体   繁体   English

具有EF CodeFirst的WPF MVVM

[英]WPF MVVM with EF CodeFirst

Database is not creating while running my WPF application. 运行WPF应用程序时未创建数据库。 What's wrong with my code: 我的代码有什么问题:

在此处输入图片说明

App.config App.config中

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

POCO class 1 : 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 class 2 : POCO 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 : 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 );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM