如何指定实体框架4.0型号的SQL Server XML数据类型?数据类型、实体、框架、型号

2023-09-04 00:07:32 作者:久居深海蓝透人心

我建立的模型首先图案使用实体框架4.0(CT​​P5)一个ORM。一些我的实体具有复杂的(对象树)属性不需要的ORM实体 - 他们仅感兴趣的后端使用此数据库,而不是使用该数据库的客户机服务器系统。

I'm building an ORM using Entity Frameworks 4.0 (CTP5) in the Model-First pattern. A few of my entities have complex (object tree) properties that don't need to be ORM entities - they're only of interest to back-end server systems that use this database, not to the clients that use this database.

我可以只序列化属性的对象树到一个字符串,并将其在数据库中存储为一个字符串,但在SQL Server XML数据类型确实有吸引力。为了能够通过查询XML数据内容,以智能的方式将是非常好的。

I could just serialize the property's object tree down to a string and store it in the DB as a string, but the SQL Server XML data type is really appealing. To be able to query over the XML data contents in an intelligent manner would be very nice.

不过,我看不出有任何的方式来指定,我想在Visual Studio实体建模XML数据类型。

However, I don't see any way to specify that I want an XML data type in the Visual Studio Entity Modeler.

时完成这件事的唯一方法来指定型号字符串字段,发出DDL,然后修改DDL修改字符串字段到XML领域?这似乎是非常脆弱和写一次,永远不会改变。有没有更好的办法?

Is the only way to get this done to specify string fields in the model, emit the DDL, then modify the DDL to change the string fields to XML fields? That seems awfully brittle and write-once, change never. Is there a better way?

推荐答案

在实体框架4.0配方,拉里Tenny和Zeeshan Hirani状态XML数据类型根本不支持EF 4.0的。

In "Entity Framework 4.0 Recipes", Larry Tenny and Zeeshan Hirani state that XML data types are simply not supported by EF 4.0.

他们确实提供了一个解决办法,这是使由模型私人所产生的实体类的字符串类型属性,并创建一个新的属性(在实体类的自己的部分类),从内部字符串返回的XElement属性:

They do offer a workaround, which is to make the string type property on the entity class generated by the model private and create a new property (in your own partial class of the entity class) to return an XElement from the internal string property:

public partial class Candidate
{
    private XElement candidateResume = null;

    public XElement CandidateResume
    {
        get 
        {
            if (candidateResume == null)
            {
                candidateResume = XElement.Parse(this.Resume);
                candidateResume.Changed += (s,e) =>
                {
                    this.Resume = candidateResume.ToString();
                }
            }

            return candidateResume;
        }

        set
        {
            candidateResume = value;
            candidateResume.Changed += (s,e) =>
            {
                this.Resume = candidateResume.ToString();
            }
            this.Resume = value.ToString();
        }
    }
}

创建所需的XML类型像这样应该可行,但对原字符串属性(简历)和新的shadow属性(CandidateResume)的每一个变化的字符串和XML之间的转换的阴影属性是pretty的昂贵。

Creating a shadow property of the desired XML type like this should work, but the conversion between string and XML on every change of the original string property (Resume) and the new shadow property (CandidateResume) is pretty expensive.

如果任何人有任何更好的想法,我还是愿意接受建议。

If anyone has any better ideas, I'm still open to suggestions.