C# 如何使用linq to实体构建类似SelectBy示例的查询?
如何使用linq to实体构建类似SelectBy示例的查询 例如:C# 如何使用linq to实体构建类似SelectBy示例的查询?,c#,linq,entity-framework,linq-to-entities,C#,Linq,Entity Framework,Linq To Entities,如何使用linq to实体构建类似SelectBy示例的查询 例如: public class Person { public string Name {get; set;} public int Age {get; set;} public string City {get; set;} } 如果我有一个新的Person(),其所有属性的值都为null,则查询应返回Person表的所有记录 但是如果我传递一个属性Age=25的对象,查询应该返回Age=25
public class Person
{
public string Name {get; set;}
public int Age {get; set;}
public string City {get; set;}
}
如果我有一个新的Person(),其所有属性的值都为null,则查询应返回Person表的所有记录
但是如果我传递一个属性Age=25的对象,查询应该返回Age=25的所有记录
我想构建一个单一的查询过滤器,以接受任何属性,如果要忽略它,则将其设置为null。首先,您的示例不能将所有属性设置为null,因为
Age
不可为null
无论如何,它是这样做的:
public static IQueryable<Person> QueryByExample(Person example, YourContext context)
{
var query = context.Persons;
if (example.Name != null)
{
string name = example.Name;
query = query.Where(p => p.Name == name);
}
// Same for other properties
return query;
}
publicstaticiQueryByExample(个人示例,YourContext)
{
var query=context.Persons;
if(example.Name!=null)
{
string name=example.name;
query=query.Where(p=>p.Name==Name);
}
//其他属性也一样
返回查询;
}
您需要一个自定义Linq方法。以下是您如何做到这一点:
这可以帮助您动态地迭代类属性
在Person类中,Age应该是可空的(int?而不是int)。您可以每分钟收集一个这样的对象,直到满足您的要求为止。
var p = new Person {Age = 25};
src.Where(el => p.Age == null ? true : el.Age == p.Age)
.Where(el => p.Name == null ? true : el.Name == p.Name)
.Where(el => p.City == null ? true : el.City == p.City);