tags:

views:

42

answers:

2

Heres an interesting issue, I'm trying to check if a LINQ Entity exists in its table, but at design time I dont know what type that entity is. So I figure I'll just get the table, and try the Contains method on it. But I cant get the table in such a way that I can query it at design time.

I've tried the GetTable method on the datacontext, but I dont know how to cast it to the appropriate type when using GetTable(Of). GetTable(Type) works, I just use Entity.GetType(), but then I don't know how to query the ITable thats returned.

To try and cast the ITable to something useable, I created an interface(IWhatever) that could implement properties that are native to all of my entities I would encounter. I then attempted a CType(GetTable(Entity.GetType()), IEnumerable(Of IWhatever))) No luck.

Any ideas, or am I just going about this completely wrong?

Example:

Public Function EntityExists(ByVal Entity As Object, ByVal DataContext As MyDataContext) As Boolean
    Dim T as Type = Entity.GetType()

    Dim EntityITable as ITable = DataContext.GetTable(T)

    'Do something to see if ITable contains Entity    

End Function
A: 

I don't know the vb.net syntax, so I'll have to do this is C#:

public bool EntityExists<T>(T Entity, MyDataContext DataContext)
{    
    ITable<T> EntityITable  = DataContext.GetTable<T>();
    return EntityITable.Contains(Entity);
} 

The Vb.net, I imagine, would be something like:

Public Function EntityExists(Of TEntity)(ByVal Entity As TEntity, _
                 ByVal DataContext As MyDataContext) As Boolean 

    Dim EntityITable as ITable(of TEntity) = DataContext.GetTable(of TEntity)()

    Return  EntityITable.Contains(Entity)
End Function
James Curran
Ahh, yea thats what I'm lookin for. A little more research into it and it works now. Thanks!!!
instantmusic
A: 

The End Result:

Public Function EntityExists(Of TEntity As Class)(ByVal Entity As TEntity, ByVal DataContext As System.Data.Linq.DataContext)

    Dim EntityITable As System.Data.Linq.Table(Of TEntity) = DataContext.GetTable(Of TEntity)()
    If EntityITable.Contains(Entity) Then
        Return True
    Else
        Return False
    End If

End Function

It can be used by:

Dim Exists As Boolean = EntityExists(Entity, DataContext)
instantmusic