zoukankan      html  css  js  c++  java
  • C#/.NET VS2017+ EF+SQLite.CodeFirst——真正实现CodeFirst

    本文所介绍的是真正的EF+CodeFirst,不需要提前建表,由代码自动生成!

    进行前需要准备的:

    1、下载Sqlite Expert
    http://www.sqliteexpert.com/download.html

     2、下载后新建数据库,然后保存到你指定的目录即可(保存为.db文件)

    不需要新建表

    然后在VS中->工具->扩展和更新->联机

    搜索SQLite/SQL Server Compact ToolBox ,下载完后重启VS###

    (这个插件安装后,在选择数据源时已经可以选择SQLite了,但是保存的时候会提示失败,还需要安装另一个插件)

    在同一个地方再搜索dotConnect ADO.NET Data Provider for SQLite,记得不是安装Standard的,点下载后会出现个弹出框下载,下载完后安装时要先关闭VS

     

    3然后开始敲重点了

    1) 先在NuGet中添加相关依赖项:Entity Framework,SQLite、System.Data.SQLite、System.Data.SQLite.EF6和SQLite.CodeFirst;

    (始终复制至本地)

    2)添加命名空间

     using System.Data.Entity;

    using SQLite.CodeFirst; 

    3. 定义实体类(数据类型需要和数据库保持一致,否则报错)

    public class UsersInfo
    {
    public int Id { get; set; } = 1;

    public string Name { get; set; } = "2";

    public string Password { get; set; } = "1";

    public int RoleId { get; set; } = 0;
    }

    4. Model配置类

    class UserConfig: EntityTypeConfiguration<UsersInfo>
    {
    public UserConfig()
    {
    this.ToTable("T_Users");
    }
    }

    添加Context类,继承自DbContext

    public class MyDbContext:DbContext
    {
    public MyDbContext():base("name=SQLiteConnect")
    {

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    base.OnModelCreating(modelBuilder);

    Assembly ass = Assembly.GetExecutingAssembly();
    modelBuilder.Configurations.AddFromAssembly(ass);
    }
    }

    5. 获取数据库连接字符串
    工具->连接到数据库->更改->选择SQLite Database->Browse数据库文件->测试成功后复制Connection String

     

    5. 修改配置文件APP.config
    5.1 在</system.data>结点后面添加连接字符串(其中相对路径可以"Data Source=.SQLLiteTest.db" )
    <connectionStrings>
    <add name="SQLiteConnect" connectionString="Data Source=F:xxxSQLLiteTest.db" providerName="System.Data.SQLite.EF6"/>
    </connectionStrings> 
    5.2 添加Provider结点(主要原因是SQLite的invarianName不是在自动生成的.EF6里面)

    <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />

    如不进行provider注册,后续操作会出现以下错误

    6. 新建窗体测试
    6.1 界面窗口布局

    6.2 按钮事件
    private void btnAdd_Click(object sender, EventArgs e)
    {
    List<Student> books = new List<Student>()
    {
    new Student() {ID=1, Name = "小明", Age = 11, Gender = "男" },
    new Student() {ID=2, Name = "老王", Age = 12, Gender = "男" },
    new Student() {ID=3, Name = "小郭", Age = 10, Gender = "女" },
    new Student() {ID=4, Name = "小李", Age = 11, Gender = "男" },
    new Student() {ID=5, Name = "小玉", Age = 9, Gender = "女" },
    };

    using (var db = new StudentContext())
    {
    db.Students.AddRange(books);
    int count = db.SaveChanges();
    this.Text = $"{DateTime.Now}, 插入{count}条记录";
    }
    }
    private void btnModify_Click(object sender, EventArgs e)
    {
    using (var db = new StudentContext())
    {
    var students = db.Students.FirstOrDefault(x => x.Name == "小李");
    if (students != null)
    {
    students.Age += 1;
    int count = db.SaveChanges();
    this.Text = $"{DateTime.Now}, 修改{count}条记录";
    }
    }
    }

    private void btnDel_Click(object sender, EventArgs e)
    {
    using (var db = new StudentContext())
    {
    var students = db.Students.FirstOrDefault(x => x.Name == "小玉");
    if (students != null)
    {
    var result = db.Students.Remove(students);
    int count = db.SaveChanges();
    this.Text = $"{DateTime.Now}, 删除{count}条记录";
    }
    }
    }

    private void btnQuery_Click(object sender, EventArgs e)
    {
    using (var db = new StudentContext())
    {
    var students = db.Students.Where(x => x.Name == "老王").OrderByDescending(x => x.Age).ToList();
    this.Text = $"{DateTime.Now}, 查到{students.Count}条记录";
    this.dataGridView1.DataSource = students;
    }
    }

    private void btnRefresh_Click(object sender, EventArgs e)
    {
    using (var db = new StudentContext())
    {
    var students = db.Students.ToList();
    this.dataGridView1.DataSource = students;
    }

    7. 效果
    根据代码生成表(表中主键注意要设置为自增,否则报错)

     

  • 相关阅读:
    Visual Studio 2010使用Visual Assist X的方法
    SQL Server 2000 评估版 升级到 SQL Server 2000 零售版
    双网卡多网络单主机同时访问
    开发即过程!立此纪念一个IT新名词的诞生
    delphi dxBarManager1 目录遍历 转为RzCheckTree2树
    5320 软件集合
    delphi tree 从一个表复制到另一个表
    DELPHI 排课系统课表
    长沙金思维 出现在GOOGLE的 金思维 相关搜索里啦!!
    如何在DBGrid的每一行前加一个单选框?
  • 原文地址:https://www.cnblogs.com/xiaohua19920/p/11541867.html
Copyright © 2011-2022 走看看