【UWP】利用EF Core操作SQLite

在以往开发中,一定要在vs中安装SQLite for Universal App Platform以及一款wrapper,如SQLitePCL。现在有了EntitfyFramewrok Core,我们可以更方便的操作SQLite数据库了。

准备

Nuget包,EntityFramwork.SQLite和EntityFramework.Commands,目前是预览版

创建model

根据已有或者需要创建的数据表写一个对应的model

[Table("Student")]
public class StudentModel ()
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
}

创建context

继承DbContext写一个上下文类,重写OnConfiguring方法指明目标数据库,属性Students则对应数据库中的学生表,还可以重写OnModelCreating,确立Map规则,也可以像我一样在model中用attribute

class SchoolContext : DbContext
{
    public DbSet Students { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlite("Filename=School.db");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // modelBuilder.Entity().Property( s => s.ID ).IsRequired();
    }
}

连接数据库

如果你还没有数据库,那么可以在app运行时生成一个数据库。在app.xaml.cs或者mainpage.xaml.cs中添加以下代码即可,需要注意的是,只有app第一次运行时才会创建数据库文件,不用担心重复创建的问题。

using (var db = new SchoolContext ())
{
    db.Database.Migrate();
}

如果你想使用已有的数据库文件也可以。在项目中添加相应的数据库文件后,右键属性设为content和copy if newer/copy always。需要指出的是,EF会在LocalFolder而不是InstallLocation中寻找OnConfiguring里设置的文件名,因此我们需要先把数据文件从InstalledLocation复制到LocalFolder,再操作数据库。

操作数据库

这里就用添加一个学生数据为例

StudentModel stu = new StudentModel();
stu.ID = 1234;
stu.Name = "Hello World";

var db = new SchoolContext ();
db.Students.Add(stu);
db.SaveChanges();

Happy Coding!

posted @ 2016-04-13 16:12  苹果没有熟  阅读(849)  评论(0编辑  收藏  举报