EF Core 目前已经非常完善了。值转换在2.1就支持了。具体版本有兴趣的可以看看

运行环境

SQL Server 2005
.Net 5

值转换注意事项

枚举类型不能转char

枚举转数据库varchar非常容易,直接使用Fluent API或者属性设置转换格式

// Fluent API
builder.Entry<Person>.Property(e => e.Level).HasConversion(v => v.ToString(), v => (Level)Enum.Parse(typeof(Level), v));
// 或者使用内置的转换器
builder.Entry<Person>.Property(e => e.Level).HasConversion<string>();

// 或者喜欢用属性的也可以
public class Person {
	[Column(TypeName = "varchar(1)")] // 就这句就可以了,默认转成varchar
	public Level Level{get;set;}

}

public enum Level
{
	High,
	Low
}

关键的地方来了,char不行,插入会提示NULL,及数据丢失了。

public class Person {
	[Column(TypeName = "char(1)")] // <---就这里,char就完犊子了,丢数据
	public Level Level{get;set;}	
}

bit默认值设置成boolean,会丢失数据,提示NULL

public class Person {
	[Column(TypeName = "char(1)")] // <---就这里,char就完犊子了,丢数据
	public Level Level{get;set;}	
	
	[Column(TypeName = "bit")] // <---bit,值转换没问题
	public bool IsFailed{get;set;}
}

// 默认值目前只能用Fluent API
builder.Entry<Person>.Property(e => e.IsFailed).HasDefaultValue(false); //<---这样设置后,数据就丢失了。。

datetime2在SQL Server 2008以下版本是不支持的

默认情况下,DateTime类型会默认转换为datetime2,但是低版本的数据库是不支持datetime2类型的
解决方案:

public class Person {
	[Column(TypeName = "char(1)")] // <---就这里,char就完犊子了,丢数据
	public Level Level{get;set;}	
	
	[Column(TypeName = "bit")] // <---bit,值转换没问题
	public bool IsFailed{get;set;}

	[Column(TypeName = "datetime")] // 显式指定转换类型,就解决了低版本不支持datetime2的问题了
	public DateTime BirthDay{get;set;}
}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐