FreeSql icon indicating copy to clipboard operation
FreeSql copied to clipboard

联合主键中有datetime类型时update出现异常

Open cps8 opened this issue 5 months ago • 4 comments

问题描述及重现代码:

使用泛型仓储保存联合主键中含有datetime类型的对象时,触发Can't write CLR type System.DateTime with handler type TextHandler异常,insert没有问题。 数据库类型为timestamp

/// <summary>
/// 流水号分配表
/// </summary>
public class Serial
{
    /// <summary>
    /// 业务类型前缀
    /// </summary>
    [Column(IsPrimary = true)]
    public string BizTypePrefix { get; private set; }
    /// <summary>
    /// 日期
    /// </summary>
    [Column(IsPrimary = true)]
    public DateTime Date { get; private set; }

    /// <summary>
    /// 最后使用流水号
    /// </summary>
    public int LastValue { get; private set; }
}

public class SerialRepository : ISerialRepository
{

    private readonly IBaseRepository<Serial> _serialRepository;

    public SerialRepository(IBaseRepository<Serial> serialRepository)
    {
        _serialRepository = serialRepository;
    }
    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="serial"></param>
    /// <returns></returns>
    [Transactional]
    public Task<Serial> SaveAsync(Serial serial, CancellationToken cancellationToken = default)
    {
        return _serialRepository.InsertOrUpdateAsync(serial, cancellationToken);
    }

    [Transactional]
    public Task<int> UpdateAsync(Serial serial, CancellationToken cancellationToken = default)
    {
        return _serialRepository.UpdateAsync(serial, cancellationToken);
    }
}
// c# code

数据库版本

postgres (PostgreSQL) 16.4

安装的Nuget包

FreeSql.Provider.PostgreSQL 3.5.209

.net framework/. net core? 及具体版本

.net 8

cps8 avatar Jul 07 '25 11:07 cps8

不要用 datetime 做主键,这个兼容性不好,不同的库对精度的支持不一样。强烈不建议这样做。

2881099 avatar Jul 08 '25 03:07 2881099

其实是要用dateonly的,不过仓储在读取时报Year, Month, and Day parameters describe an un-representable DateTime. 所以才用了datetime。 既然如此 我改用string存储 在代码中转换吧

cps8 avatar Jul 08 '25 06:07 cps8

DateOnly .net6 才支持,要兼容新老 .net 运行平台。

用字符串最好

2881099 avatar Jul 08 '25 06:07 2881099

我认为,对于同一个数据库表来说,在没有权限限制的情况下,能insert就应该可以update才对,这种情况是不应该有兼容性问题

cps8 avatar Jul 08 '25 07:07 cps8