当前位置:网站首页>如何让 EF Core 6 支持 DateOnly 类型
如何让 EF Core 6 支持 DateOnly 类型
2022-06-27 03:36:00 【dotNET跨平台】
前言
上次,我们发现《DateOnly 和 TimeOnly 类型居然不能序列化》。
但问题还不仅仅如此。
问题重现
假设有下列实体类:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateOnly Birthday { get; set; }
}由于Birthday只需要日期,所以我们使用了DateOnly类型。
但是,在使用 EF Core 6 存储到数据库时,出现如下错误:
由于数据库没有 DateOnly 类型,我们使用的是 datetime 类型
结果DateOnly不能被 Map 成datetime数据库类型。
重载 OnModelCreating
根据提示,我们重载了OnModelCreating方法,发现有个HasColumnType方法,用于配置属性在面向关系数据库时映射到的列的数据类型:
modelBuilder.Entity<User>()
.Property(t => t.Birthday)
.HasColumnType("datetime");但是,没有任何效果。
HasConversion 方法
继续查找,发现还有个HasConversion方法,用于配置属性,以便在写入数据库之前转换属性值并在从数据库中进行读取时转换回:
modelBuilder.Entity<User>()
.Property(t => t.Birthday)
.HasConversion(
d => d.ToDateTime(TimeOnly.MinValue),
d => DateOnly.FromDateTime(d));现在,EF Core 6 已经可以正确地处理 DateOnly,并使用datetime数据库类型来存储它。
结论
今天,我们介绍了使用转换器来告诉 EF Core 6 如何处理 DateOnly。
添加微信号【MyIO666】,邀你加入技术交流群
边栏推荐
- Method of decoding iPhone certificate file
- ERP demand and sales management Kingdee
- [promise I] introduction of promise and key issues of hand rolling
- 455. distribute biscuits [distribution questions]
- 2021:Greedy Gradient Ensemble for Robust Visual Question Answering
- Games101 job 7 improvement - implementation process of micro surface material
- QIngScan使用
- Test the respective roles of nohup and &
- Interview-01
- Basic functions of promise [IV. promise source code]
猜你喜欢

I found a JSON visualization tool artifact. I love it!

fplan-电源规划

Super detailed, 20000 word detailed explanation, thoroughly understand es!

使用promise的基本功能【四、Promise源码】

Fplan power planning

Ledrui ldr6035 usb-c interface device supports rechargeable OTG data transmission scheme.

Anaconda3 is missing a large number of files during and after installation, and there are no scripts and other directories

GAMES101作业7提高-微表面材质的实现过程

PAT甲级 1024 Palindromic Number

Quicksand painting simulator source code
随机推荐
解码苹果手机证书文件方法
投资理财产品的钱有保障吗?会不会没有了?
Test the respective roles of nohup and &
Usage knowledge of mobile phones in new fields
静态时序分析-OCV和time derate
与STM32或GD32替换说明
Pat grade a 1021 deep root
How does source insight (SI) display the full path? (do not display omitted paths) (turn off trim long path names with ellipses)
ERP需求和销售管理 金蝶
文旅夜游|以沉浸式视觉体验激发游客的热情
QIngScan使用
Servlet and JSP final review examination site sorting 42 questions and 42 answers
Uni app's uparse rich text parsing perfectly parses rich text!
苹果唯一图谱架构常识
PAT甲级 1021 Deepest Root
ESP8266
Ldr6028 OTG data transmission scheme for mobile devices while charging
2016Analyzing the Behavior of Visual Question Answering Models
Crowd simulation
Getting started with Scala_ Immutable list and variable list