SqlSugar 对应数据库 TIME类型

数据库只存时间,不存日期,ORM框架SqlSugar应该怎么定义字段

在SqlSugar中,对应数据库的TIME类型,可以使用TimeSpan类型来表示时间。SqlSugar会在执行数据库操作时,自动处理TimeSpan与数据库的TIME类型之间的转换。

以下是一个简单的示例,演示如何在实体类中使用TimeSpan来映射数据库的TIME字段:

 

using SqlSugar;
using System;
 
// 定义实体类
[SugarTable("YourTableName")] // 替换为你的表名
public class YourEntity
{
    // 其他属性...
 
    [SugarColumn(IsPrimaryKey = true, ColumnDataType = "time")]
    public TimeSpan TimeValue { get; set; }
 
    // 其他属性...
}
 
// 使用SqlSugar客户端
var db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = "your_connection_string", // 替换为你的连接字符串
    DbType = DbType.MySql, // 替换为你使用的数据库类型
    IsAutoCloseConnection = true,
    InitKeyType = InitKeyType.Attribute
});
 
// 添加记录示例
var entity = new YourEntity
{
    TimeValue = new TimeSpan(0, 10, 30, 0), // 10:30:00
    // 其他属性赋值...
};
 
db.Insertable(entity).ExecuteCommand();
 
// 查询记录示例
var list = db.Queryable<YourEntity>().ToList();

YourEntity类的TimeValue属性使用SugarColumn特性来指定其对应数据库中的time类型。在插入和查询时,SqlSugar会自动处理TimeSpan和数据库的time类型之间的转换。

 

posted @ 2024-12-26 13:56  ziff123  阅读(191)  评论(0)    收藏  举报