[英]C# Pass entity property to a function to use in LINQ
Imagine I have a class like this:想象一下我有一个这样的 class:
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.我想在这个 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.问题是我不知道如何传递 Property/PropertyName。 The ideal way for calling it would be:
调用它的理想方式是:
string val = _myRepo.GenerateUniqueStringFor(x => x.PropertyName);
If I understand correctly, you can try to pass a delegate Func
如果我理解正确的话,你可以尝试传递一个委托
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.