.net的轻量级ORM -- PetaPoco/NPOCO框架使用说明

.net的轻量级ORM -- PetaPoco/NPOCO框架使用说明
(具体参看:http://www.toptensoftware.com/petapoco/)

  从11年就开始尝试使用轻量级ORM:PetaPoco,下文是基本使用方法。另外NPoco是PetaPoco的升级版,是另外一个人维护,原版PetaPoco基本不再维护。NPoco大多数用法和PetaPoco一致,另外有些额外的功能。NPoco我会考虑再写一篇文章介绍。

  运行查询

  首先定义POCO
  注:POCO意思是Plain Old CLR Object即指一般指带有无参构造函数只有get set的简单.net类:

// Represents a record in the "articles" table
public class article
{
  public long article_id { get; set; }
  public string title { get; set; }
  public DateTime date_created { get; set; }
  public bool draft { get; set; }
  public string content { get; set; }
}

查询

// Create a PetaPoco database object
var db=new PetaPoco.Database("connectionStringName");

// Show all articles 
foreach (var a in db.Query<article>("SELECT * FROM articles"))
{
Console.WriteLine("{0} - {1}", a.article_id, a.title);
}

注意: Database有Fetch和Query两个方法

Fetch返回List<T>.
而Query通过yield return 返回,使得不用遍历记录不用通过转载整个数据到内存里面.

注意:少量数据用Fetch更方便,大量数据而且只是单向遍历或者返回请用Query,以节约内存.

返回单个值

long count=db.ExecuteScalar<long>("SELECT Count(*) FROM articles");

返回单条记录

var a = db.SingleOrDefault<article>("SELECT * FROM articles WHERE article_id=@0", 123));

注意:当运行SingleOrDefault返回超过1条记录会报错

分页查询

注意:所有大数据量查询请都使用这个分页的方法,PetaPoco的分页查询是数据库分页.

var result=db.Page<article>(1, 20, // <-- page number and items per page
"SELECT * FROM articles WHERE category=@0 ORDER BY date_posted DESC", "coolstuff");

会返回

public class Page<T> where T:new()
{
  public long CurrentPage { get; set; }
  public long ItemsPerPage { get; set; }
  public long TotalPages { get; set; }
  public long TotalItems { get; set; }
  public List<T> Items { get; set; }
}

运行分页方法,实际上PetaPoco会执行两件事:

返回匹配的所有总记录数.
得到需要的页数的字记录数.

注意:PetaPoco会把你的sql转换成分页sql,所以对sql有一定限制,请不要用select * 而且写得sql严格用空格分开,避免PetaPoco不能正确地解析你的sql.

新增,更新,删除记录
新增

// Create the article
var a=new article();
a.title="My new article";
a.content="PetaPoco was here";
a.date_created=DateTime.UtcNow;

// Insert it
db.Insert("articles", "article_id", a);
// by now a.article_id will have the id of the new article

更新

// Get a record
var a=db.SingleOrDefault<article>("SELECT * FROM articles WHERE article_id=@0", 123);
// Change it
a.content="PetaPoco was here again";
// Save it
db.Update("articles", "article_id", a);

可以用匿名对象更新,以下是仅更新title的例子
db.Update("articles", "article_id", new { title="New title" }, 123);

装饰你的Poco

// Represents a record in the "articles" table
[PetaPoco.TableName("articles")]
[PetaPoco.PrimaryKey("article_id")]
public class article
{
public long article_id { get; set; }
public string title { get; set; }
public DateTime date_created { get; set; }
public bool draft { get; set; }
public string content { get; set; }
}

这样就可以简化操作

// Insert a record
var a=new article();
a.title="My new article";
a.content="PetaPoco was here";
a.date_created=DateTime.UtcNow;
db.Insert(a);

// Update it
a.content="Blah blah";
db.Update(a);

// Delete it
db.Delete(a);

当然也可以这样运行

// Delete an article
db.Delete<article>("WHERE article_id=@0", 123);

// Update an article
db.Update<article>("SET title=@0 WHERE article_id=@1", "New Title", 123);

也可以忽略某些属性

public class article
{
    [PetaPoco.Ignore]
    public long SomeCalculatedFieldPerhaps
    { 
        get; set; 
    }
}    

使用事务

using (var trans =db.getTransaction())
{
    // Do transacted updates here

    // Commit
    trans.Complete();
}

SQL Builder

var id=123;
var sql=PetaPoco.Sql.Builder
    .Append("SELECT * FROM articles")
    .Append("WHERE article_id=@0", id);

if (start_date.HasValue)
    sql.Append("AND date_created>=@0", start_date.Value);

if (end_date.HasValue)
    sql.Append("AND date_created<=@0", end_date.Value);

var a=db.Query<article>(sql);

也可以使用名字命名:

sql.Append("AND date_created>=@start AND date_created<=@end", 
    new 
    { 
        start=DateTime.UtcNow.AddDays(-2), 
        end=DateTime.UtcNow 
    };
);        

 

也可以这样使用

var sql=PetaPoco.Sql.Builder()
    .Select("*")
    .From("articles")
    .Where("date_created < @0", DateTime.UtcNow)
    .OrderBy("date_created DESC");

 

sql使用where in 语法可以这样

var tagsToFind = new string[] { "SqlServer", "IIS" };
var sql = PetaPoco.Sql.Builder.Select("*").From("Tags").Where("Name in (@tags)", new { tags = tagsToFind });
var result = db.Query<Tag>(sql);

生成的sql如下

select * from Tags where name in (@0, @1);
@0 = SqlServer, @1 = IIS

 

 

 

转载于:https://www.cnblogs.com/shiningplus/p/6848991.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值