EF- Result of Lambda Expression to List(of Class) - vb.net

I have the following class:
Public Class CodeList
Public Code As String
End Class
I am using Entity Framework.
I have the following table in a generated class:
Partial Public Class ContentTable
Public Property ID As Long
Public Property Type As Nullable(Of Integer)
Public Property Code As String
Public Property Active As Nullable(Of Boolean)
End Class
I am using this lambda expression to select distinct Code from ContentTable
Dim db As New ModelCodeEntities
Dim result = db.ContentTables.Select(Function(m As ContentTable) m.Code).Distinct().ToList
I want to convert the result of this lambda to a List(of CodeList)
Any help would be appreciated.

Dim result As List(Of CodeList)=db.ContentTables.Select(Function(item) item.Code).Distinct().Select(Function(code) new CodeList with{.Code=code}).ToList()

Related

How to Loop through the List in VB.NET

I have a list which is filled with a data fetched from DB.
My Code:
Dim lst As New List(Of MyClass)
lst = GetData()
MyClass looks like the following:
Public Class MyClass
Public Overridable Property Id as Integer
Public Overridable Property Questions as String
Public Overridable Property Comments as String
End Class
I am trying to loop the lst
For Each item As String In lst
'Some data manipulation
Next
But I am unable to loop it through using the above code.It throws following error:
Value of Type 'MyClass' cannot be converted to 'String'
Whats arong here? Any Help?
Thanks in advance.
Try this
For Each item As MyClass In lst
'Some data manipulation
Next

LINQ Query returning Ienumerable

I have the following 2 classes
Public Class LookupsModel
Implements IEnumerable(Of LookupModel)
Public _LookupModel() As LookupModel
Public Sub New(pArray As ArrayList)
_LookupModel = New LookupModel(pArray.Count - 1) {}
Dim i As Integer
For Each l As LookupModel In pArray
_LookupModel(i) = l
i += 1
Next
End Sub
Public Function GetEnumerator() As IEnumerator(Of LookupModel) Implements IEnumerable(Of LookupModel).GetEnumerator
Return New LookupEmum(_LookupModel)
End Function
Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return New LookupEmum(_LookupModel)
End Function
Public Property Heading1 As String
Public Property Heading2 As String
Public Property Heading3 As String
Public Property Heading4 As String
Public Property Heading5 As String
Public Property Heading6 As String
Public Property CalledBy As String
Public Property ParmName1 As String
Public Property ParmName2 As String
Public Property ParmName3 As String
Public Property ParmName4 As String
Public Property ParmName5 As String
Public Property ParmName6 As String
Public Property ValueFieldGetter() As Func(Of LookupModel, String)
Public Property DescriptionFieldGetter() As Func(Of LookupModel, String)
End Class
Public Class LookupModel
Public Sub New(ByVal Key As String, Optional ByVal Desc As String = Nothing, Optional Extra_1 As String = Nothing, Optional Extra_2 As String = Nothing, Optional Extra_3 As String = Nothing, Optional Extra_4 As String = Nothing)
Me.Field1 = Key
Me.Field2 = Desc
Me.Field3 = Extra_1
Me.Field4 = Extra_2
Me.Field5 = Extra_3
Me.Field6 = Extra_4
End Sub
Public Sub New()
Me.Field1 = Nothing
Me.Field2 = Nothing
Me.Field3 = Nothing
Me.Field4 = Nothing
Me.Field5 = Nothing
Me.Field6 = Nothing
End Sub
Public Property Field1 As String
Public Property Field2 As String
Public Property Field3 As String
Public Property Field4 As String
Public Property Field5 As String
Public Property Field6 As String
End Class
This is the linq query:
Dim lm As LookupsModel = GetLookupsModel(FieldID, lookup, LookupPage:=1, SearchField:=SearchField, SearchFields:=searchFields, SearchString:=String.Empty)
Dim lm2 As IEnumerable(Of LookupModel) = lm.Where(Function(p) p.Field1.Contains("A"))
I'm trying to query LookupsModel and only get the LookupModel collection where LookupModel.Field1 starts with "A". But the following query returns an Ienumerable of LookupModel, not the LookupsModel object with those items excluded. How do we accomplish this and get a LookupsModel object as a result?
You can't directly cast from an IEnumerable(Of LookpupModel) to a LookupsModel. You have a few options:
Add a constructor that takes an existing IEnumerable(Of LookupModel)
Convert the output of Where to an ArrayList and use your existing constructor.
But what's the point of LookupsModel in the first place? All you're doing is wrapping an array of LookupModel and not adding any additional functionality. Why not just stick with IEnumerable(Of LookupModel)?

Entity Framework : Error when trying to Deep clone an object

I'm using Entity Framework 6 , with Database First. The model is created using wizard from existing Sql server database.
I'm using this code to do a deep clone :
Imports System.ComponentModel
Imports System.Collections
Imports System.Data.Entity.Core.Objects.DataClasses
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Reflection
Imports System.Runtime.CompilerServices
Module Extensions
Private Function ClearEntityObject(Of T As Class)(ByVal source As T, ByVal bCheckHierarchy As Boolean) As T
If (source Is Nothing) Then
Throw New Exception("Null Object cannot be cloned")
End If
Dim tObj As Type = source.GetType
If (Not tObj.GetProperty("EntityKey") Is Nothing) Then
tObj.GetProperty("EntityKey").SetValue(source, Nothing, Nothing)
End If
If bCheckHierarchy Then
Dim PropertyList As List(Of PropertyInfo) = Enumerable.ToList(Of PropertyInfo)((From a In source.GetType.GetProperties
Where a.PropertyType.Name.Equals("ENTITYCOLLECTION`1", StringComparison.OrdinalIgnoreCase)
Select a))
Dim prop As PropertyInfo
For Each prop In PropertyList
Dim keys As IEnumerable = DirectCast(tObj.GetProperty(prop.Name).GetValue(source, Nothing), IEnumerable)
Dim key As Object
For Each key In keys
Dim childProp As EntityReference = Enumerable.SingleOrDefault(Of PropertyInfo)((From a In key.GetType.GetProperties
Where (a.PropertyType.Name.Equals("EntityReference`1", StringComparison.OrdinalIgnoreCase))
Select a)).GetValue(key, Nothing)
ClearEntityObject(childProp, False)
ClearEntityObject(key, True)
Next
Next
End If
Return source
End Function
<Extension()> _
Public Function ClearEntityReference(ByVal source As Object, ByVal bCheckHierarchy As Boolean) As Object
Return ClearEntityObject(source, bCheckHierarchy)
End Function
<Extension()> _
Public Function Clone(Of T)(ByVal source As T) As T
Dim ser As New DataContractSerializer(GetType(T))
Using stream As MemoryStream = New MemoryStream
ser.WriteObject(stream, source)
stream.Seek(0, SeekOrigin.Begin)
Return DirectCast(ser.ReadObject(stream), T)
End Using
End Function
End module
Now , I try to use this code like this :
Private Sub DoClone
Dim litm, newitm As MyObject
litm = context.MyObjects.FirstOrDefault
newitm = litm.Clone()
newitm.ClearEntityReference(True)
context.MyObjects.Add(newitm)
context.SaveChanges()
End Sub
I get an error :
An unhandled exception of type
'System.Runtime.Serialization.SerializationException' occurred in
System.Runtime.Serialization.dll
Additional information:Type
'System.Data.Entity.DynamicProxies.MyObject_F2FFE64DA472EB2B2BDF7E143DE887D3845AD9D1731FD3107937062AC0C2E4BB'
with data contract name
'MyObject_F2FFE64DA472EB2B2BDF7E143DE887D3845AD9D1731FD3107937062AC0C2E4BB:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected.
Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
This is my model that I use :
Partial Public Class Myobject
Public Property id As Integer
Public property name as string
Public Overridable Property chld As ICollection(Of chld) = New HashSet(Of chld)
Public Overridable Property chld1 As ICollection(Of chld1) = New HashSet(Of chld1)
End Class
Partial Public Class chld
Public Property id As Integer
Public Property date1 as DateTime
Public Property quantity as Integer
Public Property ParentID as integer
Public Overridable Property MyObj1 As MyObject
End Class
Partial Public Class chld1
Public Property id As Integer
Public Property nm as string
Public Property ParentID as integer
Public Overridable Property MyObj1 As MyObject
End Class

VB.NET CType: How do I use CType to change an object variable "obj" to my custom class that I reference using a string variable like obj.GetType.Name?

The code below works for the class that I hard coded "XCCustomers" in my RetrieveIDandName method where I use CType. However, I would like to be able to pass in various classes and property names to get the integer and string LIST returned. For example, in my code below, I would like to also pass in "XCEmployees" to my RetrieveIDandName method. I feel so close... I was hoping someone knew how to use CType where I can pass in the class name as a string variable.
Note, all the other examples I have seen and tried fail because we are using Option Strict On which disallows late binding. That is why I need to use CType.
I also studied the "Activator.CreateInstance" code examples to try to get the class reference instance by string name but I was unable to get CType to work with that.
When I use obj.GetType.Name or obj.GetType.FullName in place of the "XCCustomers" in CType(obj, XCCustomers)(i)
I get the error "Type 'obj.GetType.Name' is not defined" or "Type 'obj.GetType.FullName' is not defined"
Thanks for your help.
Rick
'+++++++++++++++++++++++++++++++
Imports DataLaasXC.Business
Imports DataLaasXC.Utilities
Public Class ucCustomerList
'Here is the calling method:
Public Sub CallingSub()
Dim customerList As New XCCustomers()
Dim customerIdAndName As New List(Of XCCustomer) = RetrieveIDandName(customerList, "CustomerId", " CustomerName")
'This code below fails because I had to hard code “XCCustomer” in the “Dim item...” section of my RetrieveEmployeesIDandName method.
Dim employeeList As New XCEmployees()
Dim employeeIdAndName As New List(Of XCEmployee) = RetrieveIDandName(employeeList, "EmployeeId", " EmployeeName")
'doing stuff here...
End Sub
'Here is the method where I would like to use the class name string when I use CType:
Private Function RetrieveIDandName(ByVal obj As Object, ByVal idPropName As String, ByVal namePropName As String) As List(Of IntStringPair)
Dim selectedItems As List(Of IntStringPair) = New List(Of IntStringPair)
Dim fullyQualifiedClassName As String = obj.GetType.FullName
Dim count As Integer = CInt(obj.GetType().GetProperty("Count").GetValue(obj, Nothing))
If (count > 0) Then
For i As Integer = 0 To count - 1
'Rather than hard coding “XCCustomer” below, I want to use something like “obj.GetType.Name”???
Dim Item As IntStringPair = New IntStringPair(CInt(CType(obj, XCCustomers)(i).GetType().GetProperty("CustomerId").GetValue(CType(obj, XCCustomers)(i), Nothing)), _
CStr(CType(obj, XCCustomers)(i).GetType().GetProperty("CustomerName").GetValue(CType(obj, XCCustomers)(i), Nothing)))
selectedItems.Add(Item)
Next
End If
Return selectedItems
End Function
End Class
'+++++++++++++++++++++++++++++++
' Below are the supporting classes if you need to see what else is happening:
Namespace DataLaasXC.Utilities
Public Class IntStringPair
Public Sub New(ByVal _Key As Integer, ByVal _Value As String)
Value = _Value
Key = _Key
End Sub
Public Property Value As String
Public Property Key As Integer
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCCustomer
Public Property CustomerId As Integer
Public Property CustomerName As String
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCCustomers
Inherits List(Of XCCustomer)
Public Sub New()
PopulateCustomersFromDatabase()
End Sub
Public Sub New(ByVal GetEmpty As Boolean)
End Sub
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCEmployee
Public Property EmployeeId As Integer
Public Property EmployeeName As String
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCEmployees
Inherits List(Of XCEmployee)
Public Sub New()
PopulateEmployeesFromDatabase()
End Sub
Public Sub New(ByVal GetEmpty As Boolean)
End Sub
End Class
End Namespace
From MSDN
CType(expression, typename)
. . .
typename : Any expression that is legal
within an As clause in a Dim
statement, that is, the name of any
data type, object, structure, class,
or interface.
This is basically saying you can't use CType dynamically, just statically. i.e. At the point where the code is compiled the compiler needs to know what typename is going to be.
You can't change this at runtime.
Hope this helps.
Since List(Of T) implements the non-generic IList interface, you could change your function declaration to:
Private Function RetrieveIDandName(ByVal obj As System.Collections.IList, ByVal idPropName As String, ByVal namePropName As String) As List(Of IntStringPair)
And then your troublesome line would become (with also using the property name parameters):
Dim Item As IntStringPair = New IntStringPair(CInt(obj(i).GetType().GetProperty(idPropName).GetValue(obj(i), Nothing)), _
CStr(obj(i).GetType().GetProperty(namePropName).GetValue(obj(i), Nothing)))
Of course, you could still have the first parameter by Object, and then attempt to cast to IList, but that's up to you.
ctype is used to convert in object type.

Custom ASP.NET MVC2 HtmlHelper: How to get the instance of the object passed to it?

I am working on a ASP.NET MVC2 website. For learning. I am working with the Visual Basic language.
In a view I would like to do this:
<%: Html.EditorForEnumeracion(Function(v) v.combustible%>
So, I created an HtmlHelper extension method:
Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports System.Reflection
Public Module HtmlHelpers
<Extension()> _
Public Function EditorForEnumeracion(Of TModel, TValue)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TValue))) As MvcHtmlString
'My stuff goes here
End Function
End Module
The problem is that I do not know how to get the instance of the v.combustible object that I pass to the helper. I do not care about the v object. I need to work with the combustible attribute of the v object.
Here and here seems to be how to do this, but I do not understand. Also, I work with Visual Basic, not C#.
I think that I can get the instance of the Enumeracion object through the expression parameter, but I do not understand how.
More info now.
This is my "Vehiculo" class:
Namespace Models.Automovil
Public Class Vehiculo
Public Property tipo As New Models.Enumeracion("TipoDeVehiculo")
Public Property marca As String
Public Property modelo As String
Public Property numeroDePuertas As Integer
Public Property combustible As New Models.Enumeracion("TipoDeCombustible")
Public Property potencia As Integer
Public Property fechaPrimeraMatriculacion As DateTime
Public Property version As String
Public Property precio As Decimal
Public Property descripcion As String
End Class
End Namespace
And this is my "Enumeracion" class:
Namespace Models
Public Class Enumeracion
Private bd As New tarificadorasegasaEntities
Private diccionario As New Dictionary(Of String, Integer)
Private _nombre As String
Private _clave As String
Private _valor As Integer
Public ReadOnly Property nombre As String
Get
Return _nombre
End Get
End Property
Public ReadOnly Property clave As String
Get
Return _clave
End Get
End Property
Public ReadOnly Property valor As Integer
Get
Return _valor
End Get
End Property
'More stuff here. Methods.
End Class
End Namespace
The model is the Vehiculo class.
Still not resolving this.
Thanks in advance.
You need to compile the expression into a Func(Of TModel, TValue), then call it on the model:
Dim func = expression.Compile()
Dim value = func(html.ViewData.Model)
Try like this:
<Extension()> _
Public Function EditorForMyCustomClassB(Of Vehiculo, Enumeracion)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of Vehiculo, Enumeracion))) As MvcHtmlString
Dim res = ModelMetadata.FromLambdaExpression(expression, html.ViewData)
Dim e As Enumeracion = DirectCast(res.Model, Enumeracion)
' use e here
End Function