C# 如何在LINQ to SQL select子句中使用自定义方法?
我想做一些类似于中描述的事情。然而,这篇文章来自2006年,需要作者编写的扩展方法。我希望在这一点上有更内在的东西 这里的目的是保存一个只包含可转换为T-SQL的操作的方法,并使用它在LINQ to SQL select语句中分配特定属性。如果有一个完全不同的方法来做这件事,那么我所尝试的,那也是一个有效的答案 我该怎么做C# 如何在LINQ to SQL select子句中使用自定义方法?,c#,linq-to-sql,expression-trees,C#,Linq To Sql,Expression Trees,我想做一些类似于中描述的事情。然而,这篇文章来自2006年,需要作者编写的扩展方法。我希望在这一点上有更内在的东西 这里的目的是保存一个只包含可转换为T-SQL的操作的方法,并使用它在LINQ to SQL select语句中分配特定属性。如果有一个完全不同的方法来做这件事,那么我所尝试的,那也是一个有效的答案 我该怎么做 我尝试过的 我有一个类似这样的查询: var theData = ( from inv in dc.Inventory where inv.IsDelete
我尝试过的 我有一个类似这样的查询:
var theData = (
from inv in dc.Inventory
where inv.IsDeleted == false
join data in cdc.InventoryDatas
on inv.InvKey equals data.ReInvKey
where data.ReColKey == colKey
select new MyClass {
SerialNumber = inv.SerialNumber,
Data = InventoryData.DataExpression( data ),
Name = inv.Name,
}
);
其中,InventoryData.DataExpression
定义如下:
public static Expression<Func<InventoryData, string>> DataExpression = (
d => d.TextData != null ? d.TextData
: d.IntegerData != null ? d.IntegerData.ToString()
: d.DecimalData != null ? d.DecimalData.ToString()
: d.DateData != null ? d.DateData.ToString()
: d.BooleanData != null ? d.BooleanData.ToString()
: null
);
公共静态表达式DataExpression=(
d=>d.TextData!=null?d.TextData
:d.IntegerData!=null?d.IntegerData.ToString()
:d.DecimalData!=null?d.DecimalData.ToString()
:d.DateData!=null?d.DateData.ToString()
:d.BooleanData!=null?d.BooleanData.ToString()
:null
);
但这并不完全正确。如何实现此功能?如果仅从一个表中选择数据,并且没有将同一属性的赋值语句右侧的其他表达式组合在一起,则此功能正常:
Data = InventoryData.DataExpression.Compile()( data )
同样
及
其中CompiledDataExpression
定义为
public static Func<InventoryData, string> CompiledDataExpression
= InventoryData.DataExpression.Compile();
public string GetData() {
// execute the compiled delegete on this InventoryData
var ret = InventoryData.CompiledDataExpression( this );
return ret;
}
但是,委托实际上并没有编译为T-SQL。取而代之的是,与表关联的类型的整个对象都被拉入,然后在本地对它们执行委托
当我尝试完整查询时,出现了一个错误,该查询在其他表上进行连接,并将委托分配给几个属性中的一个,其中一些属性从其他表中提取数据。看起来我可能能够使用称为LINQKit的东西,它可能实现了那篇文章中的扩展方法?明天试试。是的,LINQKit是做这种事情的方式。看看这个:
public static Func<InventoryData, string> CompiledDataExpression
= InventoryData.DataExpression.Compile();
public string GetData() {
// execute the compiled delegete on this InventoryData
var ret = InventoryData.CompiledDataExpression( this );
return ret;
}