NPoco ORM框架基础操作指南
基础查询操作
执行首次查询时:
public class UserProfile
{
public int Id { get; set; }
public string UserEmail { get; set; }
}
using (IDatabase database = new Database("connectionString"))
{
List<UserProfile> profiles = database.Query<UserProfile>("select id, userEmail from userProfiles");
}
注意:Database 实例需要手动关闭连接。
系统会根据列名与 UserProfile 属性名进行自动映射,匹配过程不区分大小写,无需额外配置。
实体映射配置
默认情况下无需特殊配置,系统会假设表名为类名,主键为"Id"字段。
常用的映射特性包括:
[Table]- 接收表名参数,用于指定对应的数据表[Key]- 标识主键字段,支持复合主键,可设置自增属性[Field]- 当字段名与属性名不匹配时使用[Ignore]- 忽略该属性,不参与映射[ReadOnly]- 标记只读字段,仅用于查询结果,不参与插入更新[Calculated]- 标记计算字段,会自动处理SQL生成[Json]- 序列化字段,使用JSON格式存储
示例代码:
[Table("UserProfileTable")]
[Key("ProfileId")]
public class UserProfile
{
public int ProfileId { get; set; }
[Field("email_address")]
public string UserEmail { get; set; }
[ReadOnly]
public string AdditionalData { get; set; }
[Ignore]
public int TemporaryValue { get; set; }
}
单条记录查询
可通过多种方式获取单一对象实例。
按主键查询
最直接的方法是使用 GetById<T>() 方法:
IDatabase database = new Database("connectionString");
UserProfile profile = database.GetById<UserProfile>(5);
条件查询
如未明确指定字段,系统会自动生成SELECT语句:
UserProfile profile = database.FirstOrDefault<UserProfile>("WHERE email_address = @0", "test@example.com");
// 或者完整SQL
UserProfile profile = database.FirstOrDefault<UserProfile>("SELECT p.* FROM UserProfileTable p WHERE email_address = @0", "test@example.com");
上述方法都提供相应的默认值版本。当无法确定记录是否存在时,建议使用带OrDefault后缀的方法,避免空引用异常。
另外还有 First<T> 和 FirstOrDefault<T> 方法,当返回多条记录时会抛出异常,适用于确保最多返回一条记录的场景。
数据修改操作
添加新记录
IDatabase database = new Database("connectionString");
UserProfile newProfile = new UserProfile()
{
UserEmail = "user@example.com",
LastAccessTime = DateTime.UtcNow
};
database.Insert(newProfile);
更新现有记录
var existingProfile = database.GetById(1);
existingProfile.UserEmail = "updated@example.com";
database.Update(existingProfile);
删除记录
var profileToDelete = database.GetById(1);
database.Delete(profileToDelete);
// 或按ID删除
database.Delete<UserProfile>(1);
保存操作
IDatabase database = new Database("connectionString");
UserProfile profile = new UserProfile()
{
UserEmail = "sample@example.com",
LastAccessTime = DateTime.UtcNow
};
database.Save(profile);
此方法会根据主键判断记录是否存在,决定执行插入或更新操作。
批量数据查询
获取全部记录
List<UserProfile> allProfiles = database.Fetch<UserProfile>();
条件筛选
List<UserProfile> activeProfiles = database.Fetch<UserProfile>("WHERE isActive = 1");
自定义SQL查询
List<UserProfile> filteredProfiles = database.Fetch<UserProfile>("SELECT p.* FROM UserProfileTable p WHERE p.isActive = 1");
延迟加载模式
警告:以下 Query<T> 方法采用延迟执行机制,只有在遍历结果时才会真正执行查询。如果不熟悉延迟执行概念,请使用 Fetch<T> 方法。
List<UserProfile> profiles = database.Query<UserProfile>("SELECT p.* FROM UserProfileTable p WHERE p.isActive = 1");
分页查询功能
主要提供两种分页查询方式。
Page<T> 分页
IDatabase database = new Database("connectionString");
Page<UserProfile> pagedResults = database.Page<UserProfile>(3, 15, "SELECT p.* FROM UserProfileTable p ORDER BY ProfileId");
其中 Page<T> 类型定义如下:
public class Page<T>
{
public long CurrentPage { get; set; }
public long TotalPages { get; set; }
public long TotalRecords { get; set; }
public long PageSize { get; set; }
public List<T> Data { get; set; }
}
注意事项:SQL语句中必须包含ORDER BY子句,以确保分页数据的一致性。第一个参数为页码(从1开始),第二个参数为每页大小。
SkipTake<T> 分页
此方法类似于LINQ中的Skip/Take操作,参数含义有所不同。第一个参数表示跳过的记录数,第二个参数表示获取的记录数:
List<UserProfile> results = database.SkipTake<UserProfile>(30, 15, "SELECT p.* FROM UserProfileTable p ORDER BY ProfileId");
事务处理支持
方法一
using (IDatabase database = new Database("connectionString"))
{
database.BeginTransaction();
// 执行数据操作
database.CommitTransaction();
}
方法二
using (IDatabase database = new Database("connectionString"))
{
using (var transaction = database.StartTransaction())
{
// 执行数据操作
transaction.Commit();
}
}