C
C#17mo ago
Camster

❔ ✅ 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.
public class Table<T> {
public string GetSql_CreateTable() {
var sql = new StringBuilder();
foreach (var prop in typeof(T).GetProperties()) {
// generate create table sql
}
return sql.ToString();
}

public string Fill(List<T> rows) {
var sql = new StringBuilder();
// generate insert sql
return sql.ToString();
}
}
public class Table<T> {
public string GetSql_CreateTable() {
var sql = new StringBuilder();
foreach (var prop in typeof(T).GetProperties()) {
// generate create table sql
}
return sql.ToString();
}

public string Fill(List<T> rows) {
var sql = new StringBuilder();
// generate insert sql
return sql.ToString();
}
}
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
phaseshift
phaseshift17mo ago
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 same
Camster
CamsterOP17mo ago
Nice, 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!
Accord
Accord17mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Camster
CamsterOP17mo ago
!close
Accord
Accord17mo ago
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.
Want results from more Discord servers?
Add your server