从项目工具NuGet包工具,下载system.data.sqlite。在App.config中增加如下一条
<!--下面是手动增加的一行--> <provider invariantName="System.Data.sqlite" type="System.Data.sqlite.EF6.sqliteProviderServices,System.Data.sqlite.EF6" />
写一个自己的实体类要引用 using System.ComponentModel.DataAnnotations.Schema;
[Table("Actress")] public class Actress { public Int64 ID { get; set; } public string Name { get; set; } public Int32 Age { get; set; } }
再写一个继承于DBContext的上下文MyContext,引用二条 using System.Data.Entity;
using System.Data.Common;
public class MyContext : DbContext { public DbSet<Actress> ActressSet { get; set; } public MyContext(DbConnection conn) : base(conn,false) { } }
先用sqliteConnection建立连接,再用sqliteCommand建立一个表,然后就可以用我们的MyContext增删改查,完整代码如下
using (sqliteConnection conn = new sqliteConnection()) { conn.ConnectionString = @"Data Source=d:\python\actress.db"; conn.Open(); using (sqliteCommand cmd = new sqliteCommand(conn)) { cmd.CommandText = @"create table if not exists Actress (ID integer primary key autoincrement,Name text not null,Age integer not null)"; cmd.ExecuteNonQuery(); using (MyContext context = new MyContext(conn)) { if (context.ActressSet.Where<Actress>(a => a.Name == "王菲").Count<Actress>() == 0) { context.ActressSet.Add(new Actress { Name = "王菲",Age = 47 }); context.ActressSet.Add(new Actress { Name = "范冰冰",Age = 37 }); context.ActressSet.Add(new Actress { Name = "柳岩",Age = 36 }); context.SaveChanges(); } var actress = (from a in context.ActressSet select a).ToList(); actress.ForEach(a => Console.WriteLine($"{a.ID} {a.Name} {a.Age}")); Console.WriteLine("======================================"); context.ActressSet.Add(new Actress { Name = "赵薇",Age=41 }); context.SaveChanges(); actress = (from a in context.ActressSet select a).ToList(); actress.ForEach(a => Console.WriteLine($"{a.ID} {a.Name} {a.Age}")); context.ActressSet.Remove(context.ActressSet.Find(4)); ; context.SaveChanges(); Console.WriteLine("======================"); actress = (from a in context.ActressSet select a).ToList(); actress.ForEach(a => Console.WriteLine($"{a.ID} {a.Name} {a.Age}")); } } } Console.WriteLine("按任意键结束"); Console.ReadKey();
小
原文链接:https://www.f2er.com/sqlite/198426.html