Entity Framework Core 1.1.0数据类型转换

Ban*_*ito 0 c# entity-framework-core

我有一个遗留数据库,用于存储用户注释(以及其他一些文本字段)作为blob数据类型,我无法更改.

我正在编写一个数据访问层,需要始终将数据转换string为从数据库中检索数据,并blob在保存时将其转换回.

EF脚手架工具生成属性作为byte[]这些实体的数据类型.

public byte[] Comment { get; set; }
Run Code Online (Sandbox Code Playgroud)

我注意到,如果我只是将实体属性类型更改为string它实际上确实正确地保存了数据,但加载数据会导致转换错误:

无法将类型为'System.Byte []'的对象强制转换为'System.String'.

(有趣的是,版本1.0.0没有抛出此错误,加载和保存工作正常.)

我的问题是......有没有一种方法可以配置EF核心,以便在我从数据库中检索数据并将其恢复到blob保存状态时自动将此数据转换为字符串?或者我是否需要编写一大堆私有getter和setter来进行这种操作?

Mat*_*ger 5

除了我对你的回答的评论,如果你不想添加getter和setter并希望有干净的代码,你也可以使用扩展方法:

public static class Extensions
{
    public static byte[] GetBytes(this string @this, System.Text.Encoding encoding = null)
    {
        return (encoding??Encoding.UTF8).GetBytes(@this);
    }

    public static string GetString(this byte[] @this, System.Text.Encoding encoding = null)
    {
        return (encoding??Encoding.UTF8).GetString(@this);
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以用这种方式与他们合作:

myentity.Comment = "my comment".GetBytes();
string comment = myentity.Comment.GetString();
Run Code Online (Sandbox Code Playgroud)

处理代码中的默认值,即UTF8,您可以将其更改为您要使用的编码,或输入其他编码

byte[] myBytes = "my comment".GetBytes(Encoding.ASCII);
Run Code Online (Sandbox Code Playgroud)

你的胜利:你不必使用每个属性指定一个getter/setter byte[]