为自定义类型创建ADO.NET映射 [英] Creating ADO.NET mapping for custom type

查看:90
本文介绍了为自定义类型创建ADO.NET映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类型,我创建,应该持久存储在数据库(在这种情况下,SQL服务器)作为guid(虽然这个问题对于一个对象可以存储为字符串,整数,等)。

I have a custom type that I created, which should be persisted in a database (in this case, SQL server) as a guid (though this question is just as valid for an object that could be stored as a string, integer, etc).

当我将此类型作为参数传递给DbCommand对象时,会出现异常:

When I pass this type as a parameter to a DbCommand object, I get an exception:


ArgumentException:没有对象类型[...]与已知托管提供程序本机类型的映射。

ArgumentException: No mapping exists from object type [...] to a known managed provider native type.

在类上允许隐式转换为字符串或guid的CType运算符,但.NET不使用这些,因为它不知道它应该转换类型。

I have CType operators on the class that allow implicit conversion to a string, or a guid, but .NET doesn't use these since it doesn't know it should convert the type.

有没有办法添加一个类型到内部映射,或者告诉.NET如何存储我的自定义类型在数据库中?

Is there a way to add a type to the internal mapping, or otherwise tell .NET how to store my custom type in the database?

我显然可以转换在将它传递给.NET的东西时,类型自己,但我希望这会自动发生,就像大多数内置类型。

I obviously can convert the type myself when passing it to the .NET stuff, but I'd like this to happen automatically, like it does for most of the built-in types.

我试图为我的类型实现一个TypeConverter类(继承自TypeConverter,覆盖CanConvertFrom,CanConvertTo,ConvertFrom,ConvertTo,IsValid,并将System.ComponentModel.TypeConverter属性添加到我的类),但这仍然不工作。

I've tried to implement a TypeConverter class for my type (inherits from TypeConverter, overrides CanConvertFrom, CanConvertTo, ConvertFrom, ConvertTo, IsValid, and added the System.ComponentModel.TypeConverter attribute to my class), but this still doesn't work.

我假设它缺少一个告诉.NET在数据库中存储值时要转换的类型。

I'm assuming it's missing a piece telling .NET what type to convert to when storing the value in the database.

我的解决方法是,现在,我拦截参数列表, ,并有一个方法,将我的自定义类型更改为guid。这是脏的,但它现在工作,但我仍然认为这个问题是未回答。

My workaround for this, for now, is that I intercept the list of parameters, before I pass them to SQL server, and have a method that changes my custom type into a guid. This is dirty, but it does work for now, but I still think this question is unanswered.

推荐答案

根据如何将用户定义的类型传递给SqlParameterCollection.AddWithValue ?,这是不可能的。我也看过了GetMetaTypeFromValue方法,它看起来像所有的映射实际上是硬编码在框架中,因此没有用户定义映射是可能的。

According to How should I pass a user-defined type to SqlParameterCollection.AddWithValue?, it's not possible. I've looked at the GetMetaTypeFromValue method as well, and it looks like all the mapping is in fact hardcoded in the framework, thus no user-defined mapping is possible.

如何让一个给定类型定义映射的属性非常有用。

How annoying, it would be really useful to have an attribute that defines mapping for a given type.

这篇关于为自定义类型创建ADO.NET映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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