.Net Core 3: Use Entity Framework Core operating SQLite database in WPF - ZDY 'LOVE | about photography, travel, outdoors, travel notes, Raiders, feelings, programming ...

Original: .Net Core 3: Use Entity Framework Core operating SQLite database in WPF - ZDY 'LOVE | about photography, travel, outdoors, travel notes, Raiders, feelings, programming ...

Software development process, the choice is usually a local database SQLite, because its configuration is relatively simple and does not require additional database services. SQLite can be a good support for some of the basic features of a relational database included, such as standard SQL syntax, objects, data tables and indexes, and take up less resources, but also easy to use on mobile devices.

In addition, some of the features of Entity Framework (such as Fluent API, Migration, etc.) allows us to its very convenient operation SQLite, and its development team continues iteration of the project, these areas can become the reason we use EF Core.

// Entity Framework
Install-Package Microsoft.EntityFrameworkCore.Sqlite
// 提供了用于 Migration 的工具
Install-Package Microsoft.EntityFrameworkCore.Tools
public class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { set; get; }
    [MaxLength(50), Required]
    public string Name { set; get; }

    public string Age { set; get; }

    public string Sex { get; set; }
}
public class LovePlayerContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=ZDY.LovePlayer.db");
    }

    public DbSet<User> User { set; get; }
}

Open Visual Studio Management Pack console, type:

Add-Migration Migration_001

When first run, the program will automatically generate Migrations directory, file and add the following three projects under the Migrations catalog:

  • XXXXXXXXXXXXXX_Migration_001.cs - primary migration file. Contains the required application migration operation (Up ()), and reducing migration required for the operation (in Down () in).
  • XXXXXXXXXXXXXX_Migration_001.Designer.cs - migrate metadata file. EF contains information used.
  • LovePlayerContextModelSnapshot.cs-- snapshot of the current model. Adding to determine when to change the content of the next migration.

Which, XXXXXXXXXXXXXX time stamp generated by the execution time, the filename timestamp helps to keep the file in chronological order, so that you can see the changes progress.

When the database model changes, run the command again to generate a new migration .

App.xaml.cs

public App()
{
    using (var db = new LovePlayerContext())
    {
        try
        {
            using (var context = new LovePlayerContext())
            {
                // 检查是否有新的迁移
                if (context.Database.GetPendingMigrations().Any())
                {
                    context.Database.Migrate(); //执行迁移
                }
            }
        }
        catch (NotSupportedException ex)
        {
        }
        catch (Exception ex)
        {
        }
    }
}

By calling context.Database.Migrate () method, the data synchronized to the database structure, wherein, when the database file does not exist, it is created automatically.

Note Do not () Migrate called before EnsureCreated () . EnsureCreated () will bypass the migration creates the schema, which can lead to Migrate () failed.

EnsureCreated () and Migrate () difference: EnsureCreated () will automatically be created when the database does not exist, but if there is a database and data structure changes after the change will not be updated in the database.

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        using (var context = new LovePlayerContext())
        {
            if (context.User.ToList().Count == 0)
            {
                var cate1 = new User { Name = "User A" };
                var cate2 = new User { Name = "User B" };
                context.User.AddRange(cate1, cate2);
                context.SaveChanges();
            }

            // 查询
            var list = context.User.ToList();

            this.DataList.ItemsSource = list;
        }
    }
}

MainWindow.xaml

<Grid>
    <DataGrid x:Name="DataList" AutoGenerateColumns="True"></DataGrid>
</Grid>

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12293259.html