❔ ✅ Use Reflection or Generics to specify one or more properties
I'm writing something that will automatically create a table and fill it with data based on the properties of a generic object. It's for unit testing, to be built and blown away when finished, so I don't need a heavy-duty framework like EF Core. Hopefully the code below makes sense, without all the details. I'm just looping through the properties and building Create Table and Insert sql statements.
Where I'm stuck is how to specify one or more properties of the generic object to be part of a primary key. I'm not sure syntatically how to say, "use these properties for primary key". Any help would be appreciated!
5 Replies
Probably you could use an expression, then parsing the expression for the property name.
So for example with one T youd have
string Fill<T, U>(Expression<Func<T, U>> primaryProperty)
used like Fill<Foo>(foo => foo.Bar)
EF always picks prim key by looking for a property name 'Id' - you could do the sameNice, i had a feeling there was a way to do it with expression trees. I'm not very knowledgeable on them, so need to do some more research. Also, in my case, I could have composite keys. Thank you, that helps a lot!
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
!close
Closed!
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.