EF代码第一 - 映射字典或自定义类型作为nvarchar [英] EF Code First - Map Dictionary or custom type as an nvarchar

查看:584
本文介绍了EF代码第一 - 映射字典或自定义类型作为nvarchar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用EF代码,首先使用存储过程使用简单的旧ADO.NET访问数据库。

I want to use EF Code first for a database that I'm currently accessing using plain old ADO.NET with stored procedures.

在我的数据库中我有一些 nvarchar(MAX)应该映射到字典< string,string> 的列。

In my database I have some nvarchar(MAX) columns that should be mapped to and from a Dictionary<string, string>.

保存到数据库时,它是一种XML格式的字符串。我使用这种技术来允许例如在线商店中的产品名称。我不知道任何给定的用户想要翻译的语言,所以我不能为每种语言都有一个 Name 列。

When saved to database, it is an XML formatted string. I use this technique to allow internationalization of e.g. a name of a product in an online store. I don't know how many languages any given user want to translate to so I can't have a Name column for each language.

我也想避免将值存储在一个单独的表中,所以我最后用Dictionary-XML方法。

I also wanted to avoid storing the values in a seperate table, so I ended up with the Dictionary - XML approach.

我的方式现在,当我与数据库进行交互时,只需将这些列中的任何一列视为一个字符串。我有一个自定义的映射器函数,可以将XML转换成Dictionary,并返回到XML。

The way I do it now, is to just treat any of these columns as a string whenever I interact with the database. I have a custom mapper function that can turn the XML into a Dictionary, and back to XML.

但是我似乎找不到一种方法来与EF代码第一?任何想法?

But I can't seem to find a way to do this with EF Code first? Any ideas?

推荐答案

您可以添加一个将返回您的 Dictionary<,> 作为XML字符串,然后删除您的 Dictionary<,> 属性的映射。

You can add a property that will return your Dictionary<,> as a XML string and then remove the mapping for your Dictionary<,> property.

    [NotMapped]
    public Dictionary<string,string> MyDictionary
    {
     get; set;
    }

    public string DictionaryAsXml
    {
        get
        {
             return ToXml(MyDictionary);
        }
        set
        {
           MyDictionary = FromXml(value);
        }
    }

如果您不想公开您的 DictionaryAsXml 属性看看这个博文。它显示如何保持私有和受保护的属性。

If you don't want to expose your DictionaryAsXml property have a look at this blog post. It shows how you can persist private and protected properties.

这篇关于EF代码第一 - 映射字典或自定义类型作为nvarchar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆