我有这段重复的代码:
var expCodes = (from cpdet in _dataContextOrders.CodeProfileDetails
join cpd in _dataContextOrders.CodeProfileDefinitions on cpdet.CodeProfileDefinitionID equals cpd.ID
join cp in _dataContextOrders.CodeProfiles on cpd.CodeProfileID equals cp.ID
join cc in _dataContextOrders.FMSCostCentres on cpdet.CostCentreID equals cc.ID
join ec in _dataContextOrders.FMSExpenseCodes on cpdet.ExpenseCodeID equals ec.ID
where cp.ID == Convert.ToInt32(intCostCodeProfileId)
&& cpdet.CostCentreID == Convert.ToInt32(intCostCentreSelected)
&& ec.Active == true
select new
{
ec.ID,
ec.CostCentreID,
ExpenseCodeExternalRef = ec.ExternalRef,
ExpenseCodeDescription = ec.Description,
displayExpenseCode = ec.ExternalRef + " " + ec.Description
}).Distinct().OrderBy(ec => ec.displayExpenseCode);
ddlExpCode1.DataSource = expCodes;
ddlExpCode1.DataTextField = "displayExpenseCode";
ddlExpCode1.DataValueField = "ID";
我想做的是将它自己放入一个类,就像我们在LinqToSql之前做的那样,我可以从我的aspx.cs页面调用,使用2个参数,intCostCodeProfileId和intCostCodeProfileId,它将返回下拉列表的数据。
我该怎么做?
答案 0 :(得分:2)
您必须创建一个与select
语句(ID,CostCentreId等)中的属性匹配的模型类。然后将select new {
修改为select new FreshlyCreatedModelClass() {
。
从您的方法返回匿名类型的唯一方法是使用IEnumerable<object>
或IEnumerable<dynamic>
,这两者都不应该在这种情况下推荐。您的方法应返回IEnumerable<FreshlyCreatedModelClass>
(如果您需要进一步构建查询,则可以使用IQueryable<FreshlyCreatedModelClass>
。)
对模型类进行排序后,只需将代码移动到单独的方法即可。
答案 1 :(得分:-1)
创建一个普通类(例如Connection.cs)并添加如下代码:
public class MyDataSourceReturner
{
public static Object retDatasource(Object _dataContextOrders, int intCostCodeProfileId){
var expCodes = (from cpdet in _dataContextOrders.CodeProfileDetails
join cpd in _dataContextOrders.CodeProfileDefinitions on cpdet.CodeProfileDefinitionID equals cpd.ID
join cp in _dataContextOrders.CodeProfiles on cpd.CodeProfileID equals cp.ID
join cc in _dataContextOrders.FMSCostCentres on cpdet.CostCentreID equals cc.ID
join ec in _dataContextOrders.FMSExpenseCodes on cpdet.ExpenseCodeID equals ec.ID
where cp.ID == Convert.ToInt32(intCostCodeProfileId)
&& cpdet.CostCentreID == Convert.ToInt32(intCostCentreSelected)
&& ec.Active == true
select new
{
ec.ID,
ec.CostCentreID,
ExpenseCodeExternalRef = ec.ExternalRef,
ExpenseCodeDescription = ec.Description,
displayExpenseCode = ec.ExternalRef + " " + ec.Description
}).Distinct().OrderBy(ec => ec.displayExpenseCode);
return expCodes;
}
}
之后您可以像这样使用此代码:
ddlExpCode1.DataSource = MyDataSourceReturner.retDatasource(_dataContextOrders, 5);
并收到您的DataSource。