dotnetcore / FreeSql

🦄 .NET aot orm, C# orm, VB.NET orm, Mysql orm, Postgresql orm, SqlServer orm, Oracle orm, Sqlite orm, Firebird orm, 达梦 orm, 人大金仓 orm, 神通 orm, 翰高 orm, 南大通用 orm, 虚谷 orm, 国产 orm, Clickhouse orm, QuestDB orm, MsAccess orm.
http://freesql.net
MIT License
3.99k stars 842 forks source link

CreateInstance 导致可为空的DataTime 赋值为0001-01-01 时间问题 #1786

Closed ckbabby closed 1 month ago

ckbabby commented 1 month ago

问题描述及重现代码:

你好,我想问下为啥object obj = table.CreateInstance(dict); 这里代码会将updatetime 改为 0001-01-01


using FreeSql;
using FreeSql.DataAnnotations;
using FreeSql.Extensions.ZeroEntity;
using FreeSql.Internal.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Text;
using System.Text.Json;

using (var fsql = new FreeSqlBuilder()
    .UseConnectionString(DataType.Sqlite, "data source=111.db")
    .UseAutoSyncStructure(true)
    .UseNoneCommandParameter(true)
    .UseMonitorCommand(cmd => Console.WriteLine(cmd.CommandText + "\r\n"))
    .Build())
{
    var table = fsql.CodeFirst.DynamicEntity("user", new TableAttribute { Name = "t_user" })
      .Property("id", typeof(int), new ColumnAttribute { IsIdentity = true, IsPrimary = true })
      .Property("username", typeof(string), new ColumnAttribute { StringLength = 32 })
       .Property("createtime", typeof(DateTime), new ColumnAttribute {  })
        .Property("updatetime", typeof(DateTime), new ColumnAttribute { IsNullable = true })
      .Build();

    //如果有必要,请将 table 缓存起来
    if (fsql.DbFirst.ExistsTable(table.DbName) == false)
        fsql.CodeFirst.SyncStructure(table.Type); //创建表

    var dict = new Dictionary<string, object>();
    dict["id"] = 1;
    dict["username"] = "xxx";
    dict["createtime"] = DateTime.Now;

    //这里我设置updatetime 值为可为空,但是这里转换成0001-01-01 时间了,导致这个时间插入到数据库里面了
    object obj = table.CreateInstance(dict);

    fsql.Insert<object>().AsType(table.Type).AppendData(obj).ExecuteAffrows();
}

数据库版本

DataType.Sqlite

安装的Nuget包

FreeSql.All 3.2.821

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

net8

d4ilys commented 1 month ago

更改DateTime类型为可空类型

.Property("updatetime", typeof(DateTime?), new ColumnAttribute { IsNullable = true })

d4ilys commented 1 month ago

image

ckbabby commented 1 month ago

非常感谢,测试过没问题了