我有下面的Expression Func,它接收两个输入参数,第一个是Person对象,第二个是bool并返回另一种类型的对象PersonProfile
private Exression<Func<Person, bool, PersonProfile>> PersonProfileProjection => (person, isValid) =>
new PersonProfile
{
FirstName = person.FirstName,
HasAddress = isValid ? person.Address1 : null
};
并且我试图在从dbContext中获取Person表时调用它。
_dbContext.Persons.Select(PersonProfileProjection);
我很困惑如何在PersonProfileProjection内部发送布尔参数。当我只这样输入一个输入和一个输出参数时,它就可以工作。但是我也想要额外的布尔输入。
任何帮助将不胜感激。
答案 0 :(得分:0)
您可以按照Microsoft文档的说明进行操作:Expression Class
为SQLite创建的一个示例,显示了上述功能的用法。
public void GetData()
{
var connection = new SQLiteConnection(@"Data Source=database.sqlite;Version=3;");
var context = new DataContext(connection);
connection.Open();
var createtableQuery = @"
drop table Company;
CREATE TABLE[Company]
(
[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
[Seats] INTEGER NOT NULL
);
";
var command = new SQLiteCommand(createtableQuery, connection);
command.ExecuteNonQuery();
Company com = new Company()
{
Id = 6,
Seats = 7
};
context.GetTable<Company>().InsertOnSubmit(com);
context.SubmitChanges();
var companies = context.GetTable<Company>();
foreach (var company in companies)
{
Console.WriteLine("Company: {0} {1}",
company.Id, company.Seats);
}
//compile Expression using Compile method to invoke it as Delegate
Func<int,int, Company> PersonProfileProjectionComp = PersonProfileProjection.Compile();
var dd = companies.Select(p => PersonProfileProjectionComp(p.Id,p.Seats));
//// Below line inline use. Both works.
//var dd = companies.Select(p => PersonProfileProjection.Compile().Invoke(p.Id,p.Seats));
}
private System.Linq.Expressions.Expression<Func<int, int, Company>> PersonProfileProjection => (person, seats) =>
new Company
{
Id = person,
Seats = seats
};
或一行使用: PersonProfileProjection.Compile()。Invoke(人,isValid)
答案 1 :(得分:0)
您可以将其声明为Func
而不是表达式:
private Func<Person, bool, PersonProfile> PersonProfileProjection => (person, isValid) =>
new PersonProfile
{
FirstName = person.FirstName,
HasAddress = isValid // do what you meant to do
};
...,并将其称为:
_dbContext.Persons.Select(p => PersonProfileProjection(p, true));
您还可以编写一个普通方法:
private PersonProfile PersonProfileProjection(Person person, bool isValid)
{
return new PersonProfile
{
FirstName = person.FirstName,
HasAddress = isValid // do what you want to do
};
}
...并以相同的方式调用它:
_dbContext.Persons.Select(p => PersonProfileProjection(p, true));