将通用类与ObjectDataSource一起使用
时间:2020-03-05 18:50:23 来源:igfitidea点击:
我有一个要与ObjectDataSource一起使用的通用Repository <T>类。 Repository <T>位于一个名为DataAccess的单独项目中。根据来自MS新闻组的帖子(相关部分复制如下):
Internally, the ObjectDataSource is calling Type.GetType(string) to get the type, so we need to follow the guideline documented in Type.GetType on how to get type using generics. You can refer to MSDN Library on Type.GetType: http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx From the document, you will learn that you need to use backtick (`) to denotes the type name which is using generics. Also, here we must specify the assembly name in the type name string. So, for your question, the answer is to use type name like follows: TypeName="TestObjectDataSourceAssembly.MyDataHandler`1[System.String],TestObjectDataSourceAssembly"
好吧,有道理。但是,当我尝试时,该页面将引发异常:
<asp:ObjectDataSource ID="MyDataSource" TypeName="MyProject.Repository`1[MyProject.MessageCategory],DataAccess" />
[InvalidOperationException: The type specified in the TypeName property of ObjectDataSource 'MyDataSource' could not be found.]
奇怪的是,这只会在我查看页面时发生。当我从VS2008设计器中打开"配置数据源"对话框时,它正确地向我显示了我的通用存储库类中的方法。在调试时将TypeName字符串传递给Type.GetType()也会返回有效类型。那有什么呢?
解决方案
回答
做这样的事情。
Type type = typeof(Repository<MessageCategory); string assemblyQualifiedName = type.AssemblyQualifiedName;
获取assemblyQualifiedName的值并将其粘贴到TypeName字段中。请注意,Type.GetType(string),传入的值必须为
The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
因此,它可以通过在代码中传入该字符串来工作,因为该类位于当前正在执行的程序集中(我们在其中调用它),而ObjectDataSource则不在。
我们寻找的类型最有可能是
MyProject.Repository`1[MyProject.MessageCategory, DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null], DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null
回答
达伦
非常感谢帖子。我整天都在为此而战。奇怪的是,就我而言,我需要将方括号加倍,例如为代码:
MyProject.Repository`1 MyProject.MessageCategory,DataAccess,Version = 1.0.0.0,Culture = neutral,PublicKey = null,DataAccess,Version = 1.0.0.0,Culture = neutral,PublicKey = null
罗杰