首页 > 代码库 > .NET环境下,通过LINQ操作SQLite数据库

.NET环境下,通过LINQ操作SQLite数据库

//对应数据库中的某个表

[Table(Name = "main.Student")]
    public class Student
    {
        [Column(Name = "StuName", DbType = "varchar(50)")]
        public string StuName { get; set; }

        [Column(Name = "StuNo", DbType = "varchar(20)", IsPrimaryKey = true)]
        public string StuNo { get; set; }

    }

 

  public class SqliteDataContext : DataContext
    {
        public Table<Student> Students
        {
            get
            {
                return GetTable<Student>();
            }
        }

        public SqliteDataContext(IDbConnection connection) :
            base(connection)
        {
        }
    }

 

      #region LINQ操作SQLITE数据库
            SqliteDataContext context = new SqliteDataContext(sqlite.Connecttion);

            /*
             * 查询及插入数据
             */
            var stu = context.Students.SingleOrDefault(item => item.StuName.Equals("飞飞"));
            if (stu == null)
            {
                context.Students.InsertOnSubmit(new Student() {StuNo = "110525",StuName = "飞飞" });
                context.SubmitChanges();
            }
       

            /*
             * 查询及删除数据
             */
            stu = context.Students.Single(item => item.StuName.Equals("飞飞"));
            if (stu != null)
            {
                context.Students.DeleteOnSubmit(stu);
                context.SubmitChanges();
            }
          

            /*
             * 查询及修改数据
             */
            stu = context.Students.Single(item => item.StuName.Equals("飞飞"));
            if (stu != null)
            {
                stu.StuName = "吴高飞";
                context.SubmitChanges();
            }
            

            Console.ReadKey();

            #endregion