Linq2Sql: How to loop over context tables ?

I use linq2sql in my project not using direct table mapping but using sql views as link. Sometimes (all depend by other collegues) there is a reason for modify/add a table field in db structure. Ok, I think it's normally but if the table is included in a view then my context goes "BOOM!!!".

I have a context with 33 entities and every time i don't want to check one by one.

Problem: How to check if every entity doesn't have mapping problem?

Solution: Loop over every entities and call Any() method for each entity.

Description: If, for each entity in context, call Any() method then I can found where there is a mapping problem,

Code:

Private Function DoTest()
        Dim properties() As PropertyInfo
        
        properties = GetType(MyDataClassesDataContext).GetProperties()
        For Each p In properties
            If p.PropertyType.IsGenericType Then
                Dim attribs() As Object
                attribs = p.PropertyType.GetGenericArguments()(0).GetCustomAttributes(GetType(TableAttribute), False)
                If (attribs.Length > 0) Then
                    
                    If p.Name IsNot Nothing Then                                                                                         
                        resultList.Add(getItem( db.GetTable(DirectCast(db.[GetType]().GetProperty(p.Name).GetValue(db, Nothing), ITable).ElementType)))                       
                    End If
                    
                End If
            End If
        Next

End Function
Private Function getItem(ByVal o As ObjectAs ResultItem
        Dim result As ResultItem
        Dim errmsg As String
        errmsg = ""
        If TryInvokeEntity(o, errmsg) Then
            result = New ResultItem With {.ViewName = o.ToString(), .Status = "OK", .ErrorMessage = ""}
        Else
            result = New ResultItem With {.ViewName = o.ToString(), .Status = "KO", .ErrorMessage = errmsg}
        End If
        
        Return result
End Function
 
 
Private Function TryInvokeEntity(ByVal source As IQueryableByRef errmsg As StringAs Boolean
        Dim first As MethodCallExpression
        
        first = Expression.Call(GetType(Enumerable), _
                               "Any", _
                               New Type() {source.ElementType}, _
                               New Expression() {source.Expression})
        Try
            source.Provider.Execute(first)
            Return True
        Catch ex As Exception
            errmsg = ex.Message
            Return False
        End Try
        
        
End Function
 
 

No Comments