I have this repetitive piece of code:
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";
What I would like to do is to put it into a Class on its own, as we did before LinqToSql, that I can call from my aspx.cs page, using the 2 parameters, intCostCodeProfileId and intCostCodeProfileId and it will return the data for the Drop Down List.
How can I do this?
Create a normal class (e.g. Connection.cs) and add some code like this:
Afterwards you can use this code like this:
and receive your DataSource.
You have to create a model class that matches the properties in your
select
statement (ID, CostCentreId etc.). Then modify theselect new {
toselect new FreshlyCreatedModelClass() {
.The only way to return an anonymous type from your method is to use either
IEnumerable<object>
orIEnumerable<dynamic>
neither which should be recommended in this scenario. Your method should returnIEnumerable<FreshlyCreatedModelClass>
(orIQueryable<FreshlyCreatedModelClass>
could be used if you need to build the query further).After you have sorted the model class, you can simply move the code to a separate method.