.net - Strongly Cast A Reflection .GetValue() Object To A Generic DbSet?

Apr 10, 2012

I'm using EF 4.3.1 in VS 2010 (.Net 4.0) to load a number of reference tables from a database in order to bind them to controls in a WinForms app.At form load, I'm pre-fetching the data so that it's stored locally, and I'm creating a dictionary of BindingSource objects that I can use to bind the local data to the controls.The intent is to minimize the impact of the EF's self validation on a cold query in order to load forms faster and improve UI responsiveness.I've written code to create and fetch the BindingSource object for a given DbSet collection as follows:

Private _dictBindings As New Dictionary(Of String, BindingSource)
Private Sub ValidateBinding(Of T As Class)(ByRef DbCollection As DbSet(Of T))
Dim strClassName As String = DbCollection.[GetType]().GetGenericArguments(0).Name
If Not _dictBindings.ContainsKey(strClassName) Then[code].....

However, I'd like to call ValidateBinding on all DbSet collections in the Model on startup, and I'd like to use reflection to iterate through the available collections in the context because we're currently loading 66 tables and could add more later.I've written the following code:

For Each propSet As PropertyInfo In Db.GetType.GetProperties(BindingFlags.Instance Or BindingFlags.Public).Where(Function(P) P.PropertyType.IsGenericType)
ValidateBinding(propSet.GetValue(Db, Nothing))
Next

but it won't work as propSet.GetValue() returns an Object instead of DbSet(of T).I also can't cast the object to a DbSet of the appropriate type, even though I know the type through reflection.I don't have access to the C# Dynamic type,and I know it's a pain to mix generics with reflection, but is there a solution for which I can pass in a reflected DbSet to my functions?Perhaps something using Method.Invoke?

View 1 Replies


ADVERTISEMENT

Unable To Cast Object Of Type .objectquery To Type Generic.list

Sep 12, 2011

I have a question about ASP.Net, visual basic I have 2 LINQ query's, the first one works, the second one doesnt, produces a

"Unable to cast object of type 'System.Data.Objects.ObjectQuery'1[SelmaV2.Products]' to type 'System.Collections.Generic.List'1[System.String]'.

[Code]....

View 1 Replies

Cast Value Type To Nullable Enumeration Type In Generic Object If All Types Are Unknown At Write-time?

Dec 14, 2011

I have a generic Class I'm using to hold information loaded from a database.I have a method which takes a DataRow as an argument, uses the object's known column name and extracts the data from the DataRow, such that:Dim loadData As T = CType(myDataRow("myColumnName"), T))works as my default assignment in most cases.Unfortunately, due to some horrifying design constraints, some of my columns may be null, and may also be taken from enumerations.This means that when <T> is Nullable(Of SomeEnumeration) the above code does not work because I can't cast 0 directly to SomeEnumeration.Zero.Is there some way to check whether <T> is Nullable(Of [Enum])? Or some way to write a method which allows Integers to be cast to Nullable(Of [Enum])?I feel like I'm forgetting something that would allow me to write one of the other of these, but my weak google-fu is turning up nothing.

EDIT: Okay, thanks to dasblinkenlight's answer below, I can detect when this circumstance is occurring, but what I need to do now is to take a type <T> which I know is Nullable(Of SomeClass), get a type reference to SomeClass and then create a new object of type Nullable(Of SomeClass) and assign that to LoadData.My problem was that I had a lot of difficulty in finding any function which would accept baseType as an actual Type.Parse accepted baseType as a parameter, I knew baseType was an [Enum] type because of dasblinkenlight's code, so I was, in this instance, able to code a solution. It's a solution which is very specific to my problem (i.e., T is Nullable(of SomeEnumeration)), but it's a solution nonetheless.

View 2 Replies

Unable To Cast Object Of Type 'System.Collections.Generic.List`1[System.Int32]' To Type 'crmWebService.ArrayOfInt'?

May 14, 2012

I'm getting an error after sending a list to a web service.This is the code that is calling the web service:

Dim sProgramInterest As New List(Of Integer)
crmService.InsertProspectGetId(sProgramInterest.ToList)
But I'm getting this error.

[code].....

View 3 Replies

.net - Filter Custom Dictionary With LINQ ToDictionary - "Unable To Cast Object Of Type 'System.Collections.Generic.Dictionary`2"

Jul 7, 2010

I have created a Dictionary class (MyDictionary for the example). I am currently trying to pass MyDictionary into a function, filter it into a new instance of MyDictionary and pass this new instance into another method. When I am attempting to create the second instance from the filtered first instance of MyDictionary via Lambda Expressions and the ToDictionary Method, I am getting the following error:

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' to type 'MyDictionary'. I have simplified the example and recreated it in LINQPad and am getting the same error.

Here's the simplified version of my code:

[Code]...

View 2 Replies

Unable To Cast Object Of Type 'ImagesFlag' To Type 'System.Collections.Generic.IEnumerable`1[ImagesFlag]'

Jan 7, 2012

And here is the code that produces the error

CODE:

How can i cast this one?

View 1 Replies

Generic DAL Avoiding Reflection?

Oct 13, 2010

I'm working on a new DAL for my latest project. As the performance is essential I'm avoiding late binding/reflection as much as possible. One central part is the DAL function for populating Business Objects.One class is called in order to connect to the database with the given SQL (stored procedures can't be used in this environment) and the given Business Object or List is populated. As different Business Object types will be populated by the same function I made an Interface that all of the Business Objects implements with the Sub called "Fill". The question is - will reflection be used in this scenario? My thought was as I'm "describing" the objects trought the interface the compiler doesn't need to use Reflection.

[Code]...

View 3 Replies

Search Namespace For Generic Type (Reflection)

Sep 27, 2010

I'm attempting to dynamically register entities and configurations with a context (ef4 code-only). I would normally do:

Private Shared Sub ConfigureDatabase(ByRef Builder As ContextBuilder(Of ContextExtension))
'Load configurations for each of the tables (Entity sets) in our database...
ConfigureEntity(Builder, New ContactConfig)
End Sub
Private Shared Sub ConfigureEntity(Of T)(ByRef Builder As ContextBuilder(Of ContextExtension), ByVal config As EntityConfiguration(Of T), ByVal setName As String)
'Register the entity configuration with the builder
Builder.Configurations.Add(config)
'Register the entity set name with the builder
Builder.RegisterSet(Of T)(setName)
End Sub

Where ContactConfig is a class which inherits EntityConfiguration(Of Contact) and Contact is a class which implements an interface IEntity (IEntity is common to all entities). So... I need to search a namespace (say Project.DB.Client) for all signatures that match:
EntityConfiguration(Of <Class which implements IEntity>)
How can I achieve this?

View 1 Replies

.net - Cast To Generic Type At Runtime?

Sep 9, 2010

I'm in the process of creating a function which reflects over the properties in a class and adds them to this data structure I have. Some of the properties are generic types.So say we have DataType(Of T) that has a .Value property of type T:

Dim properties = GetType(MyType).GetFields(Reflection.BindingFlags.Public Or _
Reflection.BindingFlags.Instance)
For Each prop As fieldinfo In properties
Collection.Add(prop.Name,prop.GetValue(poco))
Next

In the collection.Add for primitive types (Integer, String, etc....) I just want to add the type... but in the case of generic I want to add the DataType(Of T).Value. I hope there is some work-around but I don't think there is a way because the type of T can not be determined at compile time right? Ideally DirectCast(prop.getvalue(poco), DataType(Of T)).Value would be possible. This is when you hoped even more dynamics appear than whats in .NET 4.0.

View 2 Replies

Generic List Class Cast?

Jun 10, 2010

how Inheriting List(of T) should work.It seems like what I have below should work but at runtime I get the error:[code..]

If I want to cast a List(of x) to the class xlist, how should I do that?[code...]

View 15 Replies

.net - Call To Ctype Failing At Runtime For Cast From Int To Generic Type?

Feb 25, 2011

I know about the existence of System.Nullable(Of T) Structure.I am trying to write a class to replace it: The Nullable(Of T) Class [VB code below]. But when I tested the Nullable(Of T) Class (See NullableOfTClassTest Class, Method Main) an exception occurs when using the CType operator to convert from System.Int32.Why does this happen at runtime, why isn't my Ctype operator method being called?

NOTE: code below reordered and reduced in order to hilite problem.

Namespace MyNamespace
Public NotInheritable Class NullableOfTClassTest
Private Sub New()
End Sub

[Code]...

View 2 Replies

Write To My Own App.config Using A Strongly Typed Object?

Jun 25, 2009

The following code has two flaws, I can't figure out if they are bugs or by design. From what I have seen it should be possible to write back to the app.config file using the Configuration.Save and according to[url]... the code should work.

The bugs are shown in the source below and appear when you try to set the property or save the config back out.[code]...

View 5 Replies

Strongly-typed Generic Method Invokes Its Argument's Base Class Method Instead Of A Shadowed Method In T?

Oct 19, 2010

Consider a MyForm class that contains a shadowed implementation of Show(). It also contains a CreateForm() method, which accepts an instance of the form and calls the shadowed sub:

[Code]....

View 3 Replies

Asp.net - Provide Strongly Typed Access To The Session Object

Nov 6, 2009

What is the best way to provide strongly typed access to the session object? I am planning on turning on Option Strict, which is causing the compiler to complain about my lazy programming technique of directly accessing the session object:

Dim blah As Integer = Session("Blah")

My initial thought is to create a class that wraps the session and provides strongly typed properties for the information stored in the session. However, I cannot decide if the class should be a singleton, or instantiated on every use, or where the code should reside (i.e. within the web project or within a class library).

I'm leaning towards a singleton in my class library, but I don't know if that is the best solution, or if I am missing any other possibilities.

Proposed Solution:

Public Class SessionAccess
Public Shared Property Blah(ByVal session As HttpSessionState) As Integer
Get

[Code].....

View 2 Replies

Invalid Cast Exception Was Unhandled - Unable To Cast Object Of Type 'System.String' To Type 'System.Windows.Forms.TextBox'

Feb 9, 2012

Private
Sub cmdExit_Click(ByVal
sender As System.Object,
ByVal e

[code]....

View 3 Replies

Error : Unable To Cast Object Of Type 'Object' To 'CTest'

Feb 22, 2012

I have

Public stack() As CTest

I want

Public stack() As Object

The latter is giving the error "Unable to cast object of type 'Object' to 'CTest'." when used:

Dim thestack As CTest() = testdatabase.getStack
Where testdatabase.getStack simply returns stack();
Public Function getStack() As Object()
Return stack
End Function

This fixes it, but it's not ideal (for me personally):

Dim thestack As Object() = testdatabase.getStack

So if I could keep the variable as-is (Public stack() As Object) and then do something along the lines of class.stack() = CTest I should be able to do Dim thestack As CTest() = testdatabase.getStack because the object array will programmatically have changed from Object to CTest.

View 1 Replies

C# - Serializing A Dataset To A Strongly Type Business Object Property?

Nov 14, 2009

In a vb .net winforms app I am trying out something for "wide and shallow" children of a record. I use strongly typed business objects ( Strataframe ).My plan is to have a number of "child tables" collected in a dataset I drop on the form. they have no correspondence in persisted data, so the dataset is untyped and I am creating the schema through the property sheet for the tables. Each table is the datasource for a datagridview in the interface.

In my proof of concept sample, My main businessobject (CustomerBO) interacts with a SQL Server 2008 table with fields - pk, name, - and a third column which is currently varchar(max) as I considered XML but could just as easily be varbinary(max) if that works better for holding the serialized dataset.

bo.bigfield will be the strongly typed prop I want to hold the byte() array or XML or whatever that represents the dataset for that record.So, the question in a nutshell - how do I convert a dataset to a single datum and reproduce the dataset from that datum. This is my first foray into datasets, datagridviews as well so if there are better ways to accomplish any of that I'm listening.

View 1 Replies

My Resources Object - Access Resource Images Without Strongly Typing?

Jun 18, 2009

I am having a problem accessing my resource images. a brief history, my image name is the same as my item name I want to display the proper image with the associated item in a data grid, as I loop through and load my datagrid I need to combine "My.Resources._" with the item number to correctly associate the proper image.

[Code]...

View 6 Replies

Cannot Cast An Object To Its Parent Object In Visual Basic

Aug 19, 2011

In C# we can do something like this:

Honda a = new Car(); and that works but the same one doesn't work in Visual Basic.NET (I am fairly new to Visual Basic)

Dim a as Honda = new Car and it says Unable to cast object of type 'SampleApp.Car' to type 'SampleApp.Honda'.

Here is my sample code:

Module Module1
Sub Main()
Dim a As B = New A

[Code]....

View 3 Replies

Determine If Property Is Generic List<of T> Via Reflection And Loop List Items

Oct 1, 2009

I'm looping all the properties in an object via reflection:

For Each p As PropertyInfo In values.[GetType]().GetProperties()
If p.CanRead Then
'Do stuff
End If
Next

how to determine whether the property in question is a generic List(Of T)? If it is I need to loop the list itself.

I've experimented with GetType and TypeOf but have not managed to get anything working.

To clarify, I want to keep this generic. I do not want to specify the type of T, I need to loop the list items and call the ToString method on each item. T could be one of a number of different types (application specific reference types). Is it possible to do this without specifying types?

(VB.NET 2005 with .Net 2.0)

View 3 Replies

VS 2005 : Generate A Strongly Typed Xml Document Object So That One Can Simply Dot Into The Various Data Elements?

Mar 10, 2011

I have a situation where I have an xml document that has a bunch of elements that I basically use as data variables. I populate the variables from various sources and then transform the xml file to an html file for user viewing.having to remember the names of all the data elements in the file is somewhat tedious. Is there a way to generate a strongly typed xml document object so that one can simply dot into the various data elements?

View 5 Replies

How To Use Reflection On COM Object

Sep 23, 2011

I'm wondering if there's a way to use Reflection to inspect properties of a COM object? GetType() doesn't want to return the actual type.

View 3 Replies

C# - Get Object Function Using Reflection?

Jul 19, 2011

I know how to get the properties using reflection but how would you get the function name and type of a property:

For Example: Combobox.Items.Add

I would like to get the info. for "Add" with reflection. Is this possible in .Net?

View 3 Replies

Reflection When Object Contains Other Objects?

Nov 15, 2010

I am trying to create an object browser similar to what VS2010 uses for the quick watch window. I can use reflection to iterate through the properties and display their names and values until I get to the point in an object where the property is an object of my own creation and not a system type. I can't seem to find the correct approach to be able to iterate the properties of these "sub objects".

Below is the just of what I am trying to do
Public class myClass
property myprop a string

[code].....

View 2 Replies

Get Object Property Decription Using Reflection?

Jul 19, 2011

How to get the object description using reflection. I can get the name, value, etc... but not the decription like in .net.For example the description for .Text is "Gets or sets the text associated with this control." I thought maybe using MethodInfo, but does not give the description.

Dim MethodObj As MethodInfo
Console.WriteLine("Methods:")
For Each MethodObj In GetType(TextBox).GetMethods()
Debug.Print(MethodObj.Name & " " & MethodObj.ReturnType.ToString())
Next

View 2 Replies

Reflection - Get The Name Of The Object Passed In A Byref Parameter?

Aug 29, 2011

How can I get the name of the object that was passed byref into a method?

Example:

Dim myobject as object
sub mymethod(byref o as object)
debug.print(o.[RealName!!!!])
end sub

[code]....

I'm using this for logging. I use one method multiple times and it would be nice to log the name of the variable that I passed to it. Since I'm passing it byref, I should be able to get this name, right?This would give you the parameter name in the method and it's type, but not the name of the variable that was passed byref.

using system.reflection
Dim mb As MethodBase = MethodInfo.GetCurrentMethod()
For Each pi As ParameterInfo In mb.GetParameters()

[code]....

If you put that in "mymethod" above you'd get "o" and "Object".

View 3 Replies

Invoke HasValue On A Nullable Property Of An Object Via Reflection?

Sep 15, 2010

This function loops all properties of an object to create the updatequery to save te object to the DB.

We had to make some changes to it because of the introduction of nullable properties. If the property is nullable we would like to check the 'HasValue' property. This does works when it has a value. When the property has no value we get an 'Non-static method requires a target'-error at the CBool-line

An other way to check the 'HasValue'-prop of a property using reflection?

Private Function GetUpdateQuery(ByVal obj As Object, ByRef params As List(Of SqlParameter), Optional ByVal excl As String() = Nothing) As String
Dim sql As String = String.Empty

[Code].....

View 1 Replies

Excel Find Method - System.Reflection.Missing Object

Dec 14, 2010

I have tried several versions of this with no luck. The casting of the worksheet works as my data is entered in other parts, but I have a section where I need to add data 1 column right of the cell containing the 'str(0)' value. Most of these parameters are optional. I have even tried the System.Reflection.Missing object.

[Code]...

View 5 Replies

Cast An Object Into Its Type?

Mar 1, 2012

I have a method which receives an object as parameter. This object is always of a class I have created, it will never be something simple as string, integer, etc

In my simple example I have created a class called ClassThatWillBeUpdated that requires a type for some reason not shown in the example

Public Class ClassThatWillBeUpdated(Of T)
Private _count As Integer = 0
Public Property Count() As Integer

[Code]....

Or maybe it would be possible to call the DoWork(of T)(item) directly when creating the thread, but as far as I know it's not possible to make a thread run a method that has (of T) as that is basically what I'm looking for

Needless to say, the above code would fail during compile as I have no idea how to do it, if it's even possible. I'm using .net framework 3.5

View 1 Replies

Unable To Cast Object

Mar 9, 2012

All I am trying to do is select one school id. Do you know where I went wrong? ty

Public Function findId(ByVal table_name As String, ByVal name As String)
Try
con.ConnectionString = connection_String

[Code]......

View 2 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved