C# 将实体 属性 传递给要在 LINQ 中使用的函数
C# Pass entity property to a function to use in LINQ
假设我有一个这样的 class:
public class BaseRepo<T> where T : class
{
private readonly DbSet<T> table;
public BaseRepo(MyDbContext context)
{
this.table = context.Set<T>();
}
}
我想在此 class 中实现以下逻辑。
string GenerateUniqueStringFor(PropertyName)
{
string val = string.Empty;
do
{
val = GenerateRandomString();
}
while (this.table.FirstOrDefault(x => x.PropertyName == val) is not null);
return val;
}
问题是我不知道如何通过Property/PropertyName。理想的调用方式是:
string val = _myRepo.GenerateUniqueStringFor(x => x.PropertyName);
如果我没理解错的话,你可以试试传一个delegateFunc
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;
}
假设我有一个这样的 class:
public class BaseRepo<T> where T : class
{
private readonly DbSet<T> table;
public BaseRepo(MyDbContext context)
{
this.table = context.Set<T>();
}
}
我想在此 class 中实现以下逻辑。
string GenerateUniqueStringFor(PropertyName)
{
string val = string.Empty;
do
{
val = GenerateRandomString();
}
while (this.table.FirstOrDefault(x => x.PropertyName == val) is not null);
return val;
}
问题是我不知道如何通过Property/PropertyName。理想的调用方式是:
string val = _myRepo.GenerateUniqueStringFor(x => x.PropertyName);
如果我没理解错的话,你可以试试传一个delegateFunc
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;
}