Reading sql_variant in Entity Framework
Introduction
Although Entity Framework does not have built-in support for the sql_variant data type [1][2] of SQL Server, it is possible to work around this limitation. This article describes an approach that lets you read columns of type sql_variant using an Entity Framework EDM.
Background
We needed a read-only access to a database that makes relatively heavy use of sql_variant in an application that uses Entity Framework. Unfortunately, we quickly discovered that there is no built-in support for columns of this data type: all sql_variant columns were excluded from the wizard-generated EDM with a nasty warning. Fortunately, Entity Framework supplies two features that can be combined to read sql_variant: Complex Types and DefiningQuery. The implementation converts sql_variant to varbinary, and converts binary representations to object using a long but straightforward set of rules.
Adding sql_variant to your Model
The steps below assume that you are using Visual Studio, that your database tables exist, and that you have an imported EDM file with only sql_variant columns missing. These steps also assume basic familiarity with the Entity Framework concepts and tools.
- In Model Browser, add a new Complex Type called
SqlVariantwith two properties - aprivate stringproperty calledBaseType, and aprivate Binaryproperty calledRepresentation. - In EDM Editor, add a read-only Complex Property of type
SqlVariantfor eachsql_variantfield the EDM wizard skipped. Name the properties according to the naming conventions you adopted to match the names of their corresponding columns in the database. - Open your EDM file in XML editor, and add a
DefiningQuerytag to each entity set on tables containingsql_variantcolumns. In addition to listing all "regular" columns of your table, the query needs to include a pair of expressions for eachsql_variantcolumn:cast([mytable].[mycolumn] as varbinary) as [RepMyColumn]andsql_variant_property([mytable].[mycolumn], 'BaseType') as [BaseTypeMyColumn]. - Replace
Schema="dbo"attribute of the "mytable"EntitySetwithstore:Name="mytable" - Add two columns for each
sql_variantcolumn to each entity. Call themRepMyColumnandBaseTypeMyColumn, whereMyColumnis the name of yoursql_variantcolumn. - Switch back to EDM editor, and map
SqlVariantproperties as follows:BaseTypemaps toBaseTypeMyColumn;Representationmaps toRepMyColumn. - Download the source file attached to this article, and change its namespace to match that of your project. This adds a property of type
objectcalled 'Converted' to theSqlVarianttype. Use this column to access the value of yoursql_variant.
Implementation
High-level description of the implementation fits in a single sentence: it's a switch statement on the base type of sql_variant, followed by constructing .NET objects from binary representations.
public object Converted {
get {
if (Representation == null || BaseType == null) {
return null;
}
switch (BaseType) {
case "uniqueidentifier":
return new Guid(Representation);
case "char":
case "varchar":
return GetString(Representation);
case "nvarchar":
case "nchar":
return GetNlString(Representation);
// More cases covering other base types
...
}
throw new InvalidOperationException("Unsupported SQL type: '" + BaseType + "'");
}
}
Considering that the implementation supplied with the article supports fifteen base types, it's not surprising that there's a lot of details coded into the individual converters. However, all converters follow the same basic pattern: first, they check the array of bytes to be of the expected length, then they use BitConverter to construct elements of the result, and finally construct the result. The code converting nvarchar strings provides a good example of how the individual converters work:
private static string GetNlString(byte[] src) {
if (src.Length % 2 != 0) {
throw new InvalidOperationException("NLS format is invalid.");
}
var buf = new char[src.Length / 2];
for (var pos = 0 ; pos != src.Length ; pos += 2) {
buf[pos/2] = BitConverter.ToChar(src, pos);
}
return new string(buf);
}
Using the Code
You can now read the data from your SqlVariant columns by accessing the Converted property of the complex properties you added in step 2:
foreach (var x in myEdm.myTableWithSqlVariantDatas) {
var obj = x.MySqlVariantColumn.Converted;
...
}
Limitations
- The code lacks support for some SQL Server base types. However, you can add types that are of interest to you by following the general pattern of the implementation.
- Since this implementation provides only a read access to
sql_variantcolumns, you can neither write to these columns, nor run DB queries against their values. - The binary format the implementation "understands" is highly specific to SQL Server 2008, and therefore may stop working against future versions of the database. However, I hope that the Entity Framework team adds native support for
sql_variantbefore SQL Server team releases a binary-incompatible version of their server :-) - It goes without saying that the code supplied with this article may have bugs. It is provided as a starting point to your implementation, not as a drop-in library.
发表评论
B45GJA Mighty helpful mindset, appreciate your sharing with us.. So happy to get discovered this submit.. So pleased to possess identified this article.. certainly, investigation is having to pay off.
cHqOiz What a awesome blog this is. Look forward to seeing this again tomorrow.
mVu04N Really informative blog article. Much obliged.
pyPCIU Wow, that as what I was seeking for, what a material! existing here at this web site, thanks admin of this website.
jGcIpv This unique blog is really interesting additionally diverting. I have found many helpful stuff out of this amazing blog. I ad love to go back over and over again. Thanks!
rJy33h runescape gold original tr??s tr??s adorable en compagnie de pochette avec aide -livraison dans ces date
KAPzhL me, but for yourself, who are in want of food.
WgLoFa wow, awesome article.Really looking forward to read more. Awesome.
gHUIpL Very good post. Will read on...