PetaPoco 是一个开源轻量级ORM,够小,够快,单文件, 在GitHub上有很高的人气 1377星,几年来作者一直在更新
github: https://github.com/CollaboratingPlatypus/PetaPoco
1.添加Nugit引用后,会创建以下内容,所说的单文件就是PetaPoco.cs,项目中也可只保留此文件,Generated文件夹存放的是T4模板,用于生成实体类,如不需要可以删除
2.配置数据库连接,根据T4模板生成Model类,如不需要则可省略此步
<add name="SqlServer" connectionString="Data Source=.;uid=sa;pwd=we;database=JD;" providerName="System.Data.SqlClient"/>
3.保存后,会生成Database.cs文件内容如下:
4.如果数据库表有新增或修改字段,执行以下操作后,会自动生成相应的实体类。
3.实操:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PetaPocoDemo { class Program { static void Main(string[] args) { Person p1 = Db.Record<Person>.SingleOrDefault(1); //查询ID=1的记录 Db.Record<Person>.Delete(2); //删除ID=2的记录 Person person = new Person { Name = "曹操", Sex = "男", Age = 500 }; var db = Db.GetInstance(); db.Execute("truncate table person"); //保存一个实体 db.Save(person); db.Save(new Person { Name = "孙悟空" }); db.Save(new Person { Name = "孙悟空" }); db.Save("Person", "ID", new { Name = "张天天", ID = 3 }); //save根据主键决定是新增还是修改 //查询一个实体 person = db.Single<Person>(1); person = db.Single<Person>("where id=2"); //删除一个实体 db.Delete(person); db.Delete<Person>(1); db.Delete<Person>("where name=‘张天天‘"); } } }
CREATE TABLE [dbo].[Person]( [ID] [INT] IDENTITY(1,1) NOT NULL, [Name] [VARCHAR](50) NULL, [Sex] [VARCHAR](50) NULL, [Age] [INT] NULL, [AddTime] [DATETIME] NULL, CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO
原文:https://www.cnblogs.com/slwangzi/p/9374426.html