繁体   English   中英

实体框架核心1.1.0数据类型转换

[英]Entity Framework Core 1.1.0 Data type conversion

我有一个旧数据库,将用户注释(以及许多其他文本字段)存储为blob数据类型,我无法更改。

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

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

public byte[] Comment { get; set; }

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

无法将类型为“ System.Byte []”的对象转换为类型为“ System.String”的对象。

(有趣的是,版本1.0.0并未引发此错误,加载和保存工作正常。)

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

除了我对您的答辩者的评论之外,如果您不想添加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);
    }
}

您可以通过以下两种方式与他们合作:

myentity.Comment = "my comment".GetBytes();
string comment = myentity.Comment.GetString();

请注意代码中的默认值UTF8,您可以将其更改为要使用的编码,也可以输入其他编码,例如

byte[] myBytes = "my comment".GetBytes(Encoding.ASCII);

您的胜利:您不必使用byte[]为每个属性指定获取或设置方法

byte[]转换为string 始终需要Encoding 由于EF不知道使用哪种编码,因此这种自动转换是不可能的。

但是,您可以做的是将Comment属性标记为私有,并创建包装器属性,该属性将值转换为具有您选择的Encoding的字符串:

partial class MyEntity
{
    private string m_commentText = null;
    public string CommentText
    {
        get {
            if ((m_commentText == null) && (Comment != null)) {
                m_commentText = Encoding.UTF8.GetString(Comment);      
            }
            return m_commentText;
        }
        set {
            m_commentText = value;
            if (value != null) {
                Comment = Encoding.UTF8.GetBytes(value);
            }
            else {
                Comment = null;
            }
        }
    }
}

此解决方案将文本存储在backer字段中,以避免从byte[]string多次转换。 如果需要Comment属性保持公开状态,则需要删除backer字段,以避免数据不一致:

partial class MyEntity
{
    public string CommentText
    {
        get {
            if (Comment != null) {
                return Encoding.UTF8.GetString(Comment);      
            }
            else {
                return null;
            }
        }
        set {
            if (value != null) {
                Comment = Encoding.UTF8.GetBytes(value);
            }
            else {
                Comment = null;
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM