-1

I am used to JavaScript where you can access an object's property using a string like so:

myObject[propertyNameString]

How can I do this for my query of an entity database doing something similar to this:

Dim query = From q In db[tableName]
            Where q[columnName] = myValue
            Select z
Servy
  • 202,030
  • 26
  • 332
  • 449
h01001000
  • 261
  • 8
  • 20
  • 1
    This is not supported in c# and vb.net. What is the use case here? – Chetan Jun 15 '17 at 15:11
  • If you know the name of the property, why not just `myObject.propertyName` ? – Ňɏssa Pøngjǣrdenlarp Jun 15 '17 at 15:15
  • @ChetanRanpariya is right. You can kinda sorta do this, but the code will not look similar and be difficult to manage. [check this out](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/early-late-binding/calling-a-property-or-method-using-a-string-name#Anchor_0) – Jimmy Smith Jun 15 '17 at 15:16
  • @Plutonix Because I am using this query inside a for each loop that uses a list of table names with an inner for each loop with a list of column names. I was hoping that I could write these queries dynamically this way. – h01001000 Jun 15 '17 at 15:16
  • [Here's another example where they do this](https://stackoverflow.com/questions/7854234/entity-framework-providing-column-names-as-string-variable) but again, not really similar syntactically – Jimmy Smith Jun 15 '17 at 15:20
  • [This blog post by Scott Guthrie](https://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library) is pretty old, but sounds like what you want to do. I'm not sure from the blog if it handles the table name being dynamic, but you can probably get the type from the name and use [`DbContext.Set`](https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.set(v=vs.113).aspx#M:System.Data.Entity.DbContext.Set(System.Type)). I don't think there is an official NuGet package, but [this](https://www.nuget.org/packages/System.Linq.Dynamic/) _may_ be it. – Mark Jun 15 '17 at 17:26

1 Answers1

1

Here is how I actually went about solving this:

Dim tableName As String = "myTable" 'Set "myTable" dynamically in for loop
Dim tableObjectType As Type = Type.GetType(tableName)
Dim result = dbContext.Set(tableObjectType).Find("myPrimaryKey") 'Also set dynamically
h01001000
  • 261
  • 8
  • 20