开发者

Use Linq to Save CLR objects as Binary

Is it possible to define a custom type converter so that I can save CLR objects into a sql field using Linq?

It looks like this capability should be available. The Visual Studio 2010 Linq-to-Sql designer exposes the Type property for each auto-generated CLR property.

However, when I set the type property to system.drawing.color, I get the error:

Error   1   DBML1005: Mapping between DbType 'Binary(4)'
a开发者_如何学Cnd Type 'System.Drawing.Color' in Column 'PixelColor' of Type 'Character' 
is not supported.       0   0   

It seems like I should be able to implement this type converter somehow.


Use Color.ToArgb() and FromArgb() to convert back and forth to an int value that you can store in a dbase column. If you really want to then you can use the ColorConverter class to convert back and forth to a string, something you can stuff into your PixelColor column. Using an integer column type is a heckofalot more efficient though.


Thanks Hans.

The complete solution for me was to have 2 properties in my Linq-to-Sql class. One is ColorDb which has a type system.Int32 and directly maps to a database field. It is auto-Created by the designer. This property is set to private. A second public property ColorClr which has a type System.Drawing.Color performs the conversion and exposes the data properly typed.

Partial Public Class MyObject

    Public Property ColorClr As System.Drawing.Color
        Set(ByVal value As Color)
            Me.ColorDb = value.ToArgb
        End Set
        Get
            Return Color.FromArgb(Me.ColorDb)
        End Get
    End Property
End Class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜