We have a large number of entities which contain user ID properties, I've created a custom attribute UserIdAttribute
to annotate those models. For example:
public class MyEntity
{
[UserId]
public Guid Owner { get; set; }
}
We'll have a background service whose intention is to find user ID properties across all entities and perform lookups on them to populate another table. We'd like to find these values dynamically since the state of our models/application are undergoing constant change. I know I can achieve what I want using Microsoft.Data.SqlClient
as below:
var allUserIds = new List<Guid>();
foreach (var entityType in dbContext.Model.GetEntityTypes())
{
foreach (var property in entityType.GetProperties())
{
foreach var attribute in property.PropertyInfo.GetCustomAttributes())
{
if (attribute is MyCustomAttribute)
{
//
// do this using EF & reflection
//
using (var connection = new SqlConnection("my_conn_string"))
{
try
{
var tableName = entityType.GetTableName();
var command = new SqlCommand(
$"select {property.Name} from {tableName}",
conn);
conn.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"{entityType.ClrType.Name}.{property.Name}: {reader[property.Name]}");
}
}
finally
{
conn.Close();
}
}
}
}
}
}
PopulateUserInfoTable(allUserIds);
We would prefer use EF here, the problem is that I can't see any way to query DbSets when I only have the string representation of the DbSet name. Is this even achievable?
Aucun commentaire:
Enregistrer un commentaire