Imagine I have a class like this:
public class BaseRepo<T> where T : class
{
private readonly DbSet<T> table;
public BaseRepo(MyDbContext context)
{
this.table = context.Set<T>();
}
}
I want to implement the following logic in to this class.
string GenerateUniqueStringFor(PropertyName)
{
string val = string.Empty;
do
{
val = GenerateRandomString();
}
while (this.table.FirstOrDefault(x => x.PropertyName == val) is not null);
return val;
}
The problem is I don't know how to pass Property/PropertyName. The ideal way for calling it would be:
string val = _myRepo.GenerateUniqueStringFor(x => x.PropertyName);
CodePudding user response:
If I understand correctly, you can try to pass a delegate Func
string GenerateUniqueStringFor(Func<T,string> func)
{
string val = string.Empty;
do
{
val = GenerateRandomString();
}
while (this.table.FirstOrDefault(x => func(x) == val) is not null);
return val;
}