Here is simplified SQL of my tables, which is converted to LINQ to SQL model.
CREATE TABLE Campaign (
Id int PRIMARY KEY,
Name varchar NOT NULL
);
CREATE TABLE Contract (
Id int PRIMARY KEY,
CampaignId int NULL REFERENCES Campaign(Id)
);
Now i have classes like this (these are in different namespace, not entity classes from datamodel).
public class CampaignInfo {
public static CampaignModel Get(DataModel.CampaignInfo campaign) {
return new CampaignInfo {
Id = campaign.Id,
Name = campaign.Name,
Status = CampaignStatus.Get( c )
};
}
public int Id {get; set;}
public int Name {get; set;}
public CampaignStatus { get; set;}
}
public class CampaignStatus {
public static CampaignStatus Get(DataModel.Campaign campaign) {
return new CampaignStatus {
Campaign = campaign.Id, // this is just for lookup on client side
ContractCount = campaign.Contracts.Count()
// There is much more fields concerning status of campaign
};
}
public int Campaign { get; set; }
public int ContractCount {get; set;}
}
And than i am running query:
dataContext.Campaigns.Select( c => CampaignInfo.Get( c ) );
Other piece of code can do something like this:
dataContext.Campaigns.Where( c => c.Name == "DoIt" ).Select( c => CampaignInfo.Get( c ) );
Or i want to get list of statuses for campaigns:
dataContext.Campaigns.Select( c => CampaignStatus.Get( c ) );
Note: Results from those calls are converted to JSON, so there is no need to keep track on original db entities.
As you can see, there are two goals. To have control over what data are taken from database and reuse those structures in other places. However this approach is a huge mistake, because of that classes returning object and using it in expression tree.
Now i understand, it cannot magically create expression to make whole thing with one query. Instead it’s getting count for every campaign separately. In rather complex scenarios it’s ugly slowdown.
Is there some simple way how to achieve this ? I guess, those classes should return some expressions, but i am totally new to this field and i am not sure what to do.
The general problem, if I understand correctly, is that you have some business logic that you don’t want to have repeated throughout your code (DRY). You want to be able to use this logic inside your LINQ methods.
The general solution with LINQ (over Expression trees) is to create a filter or transformation function that returns an
IQueryableso you can do further processing on that query, before it is sent to the database.Here is a way to do this:
With this in place, you can write the following code:
Having an method that returns an
IQueryableallows you to do all sorts of extra operations, without that method knowing about it. For instance, you can add filtering:or add extra properties to the output:
This will be translated to an efficient SQL query. The query will not get more records or columns from the database than strictly needed.