Reputation: 6490
I'm trying to create a generic function that will be used to access multiple tables in my database. Is there a way to used pluralised (pluralized for the non-British!) table names with my generic function.
I may be thinking about this the wrong way (fairly new to generics/templates), but here's my code (Db
is just a global var for access to my database):
public void UpdateMyTables<TEntity>() {
// string plural = EntityObject<TEntity>.GetTableName(); // OR SOMETHING SIMILAR??
IEnumerable<EntityType> entitiesToUpdate = Db.<TEntity>; // Obviously doesn't work because TEntity is not a table name, it's an object type
foreach(<TEntity> e in entitiesToUpdate) {
e.MyColumn = "A string that I'm updating all these fields with";
}
}
So my question is: do I need to do some hackery to get the pluralised table name, or is there a function designed to return this (like GetTableName), or should I come at this from a different angle?
I also found a link that would help with the manual conversion here: Pluralising in mvc
Hugs and kisses and thanks in advance...
Upvotes: 0
Views: 203
Reputation: 7590
You can use the .Set()
method to get the IEnumerable:
IEnumerable<TEntity> entitiesToUpdate = Db.Set<TEntity>();
To get the Table Name you could possibly use the code from this blog post or this SO answer.
The foreach
should be written:
foreach(TEntity e in entitiesToUpdate) { // you can use "var" here if you prefer
e.MyColumn = "A string that I'm updating all these fields with";
}
Now, the problem is that TEntity
does not have a .MyColumn
property. If you are using this method with entities that inherit from a base class (called for example BaseEntity), which has that property, you can change the method declaration like this:
public void UpdateMyTables<TEntity>() where TEntity : BaseEntity {
This limits you to pass to call this method only with Entities that inherits from BaseEntity, but will give you access to the public properties and methods defined in BaseEntity
.
To make the code above work, Base Entity should be declared like this:
public class BaseEntity { //of course it can be abstract or an interface...
public string MyColumn { get; set; }
}
I hope I understood what you wanted to do. If you need further information let us know. :)
Upvotes: 2