2012-06-26 39 views
4

我的用例非常简单。我有一个小桌子与这样的柱:在实体框架中使用sql_variant 4

dtgTestValue sql_variant not null 

我创建了一个实体框架模型(.edmx文件),它跳过了该列的说法:

数据类型“的sql_variant”不支持;表'databaseFoo.dbo.Foobar'中的'dtgTestValue'列被排除。

我需要能够读取和写入这个特定列的值。任何关于如何处理这个相当简单的用例的建议?

+1

这里有一个[文章](http://www.codeproject.com/Articles/137509/Reading-sql_variant-in-Entity-Framework)可能有帮助。 –

+0

@TheJonasPersson:在我的搜索过程中发现了这篇文章,但它似乎是“只读”的。我需要能够读取和写入数据到该列。 –

回答

4

EF 4没有对sql_variant类型的内置支持。 This article解释了如何通过将实体映射到自定义查询来进行读取,分别捕获类型和值,然后在代码中手动解码值。

不幸的是,这个解决方案不适用于写回数据。您可以尝试mapping inserts/updates/deletes to stored procedures,但我无法确定它会起作用,因为我从未尝试过它。

2

有点迟到派对,但仍然有另一种方法来做到这一点,可以为每个要存储在数据库表中的变体“类型”创建一个单独的LINQ表类。这使您可以执行插入操作。例如;

[Table(Name = "tVariant")] 
public class tVariantDouble 
{ 
    [Column(IsPrimaryKey = true, IsDbGenerated = true)] 
    public int variantID { get; set; } 

    [Column(CanBeNull = true)] 
    public double? myVariant { get; set; } 

    [Column(CanBeNull = true)] 
    public string name { get; set; } 

    [Column(CanBeNull = false)] 
    public int typeID { get; set; } 

    public tVariantDouble() { typeID = 1; } 
}; 

[Table(Name = "tVariant")] 
public class tVariantInteger 
{ 
    [Column(IsPrimaryKey = true, IsDbGenerated = true)] 
    public int variantID { get; set; } 

    [Column(CanBeNull = true)] 
    public int? myVariant { get; set; } 

    [Column(CanBeNull = true)] 
    public string name { get; set; } 

    [Column(CanBeNull = false)] 
    public int typeID { get; set; } 

    public tVariantInteger() { typeID = 2; } 
}; 

然后这些类允许您插入传统的LINQ-to-SQL方法。我还在插入过程中将typeID设置为一个唯一值,这对于使用LINQ where语句再次选择适当类型的数据很有用。

我会建议为同一张表创建一个基本模板类,但是LINQ在继承时最好是笨重的,它根本无法工作。

这种方法确实会造成一点点重复,但仍然是一种很好的方法来完成这一任务,并且比其他建议的方法具有更少的缺点。

如果你想从表格中选择所有的数据,不管变体的类型如何,我建议使用联合运算符和一个单独的中间类来加入所有的结果。

+0

我不明白一个单词。任何例子也许? – ViRuSTriNiTy