Reputation: 51064
I have a scenario where I would like to filter some entity sets at model level, not at query level, i.e. I basically want to 'hard code' the filtering into my model, so that I don't always have to repeat the same Where method filtering in every query against an entity set. More specifically, I have a CampaignTypes
entity set, and in the data model I am busy with I only want campaign types belonging to a certain business area. Without the lower level filtering I seek, every time I query CampaignTypes
I will have to use CampaignTypes.Where(ct => ct.BusinessArea == BusinessAreas.Outdoor)
. How can I avoid this repeated filtering short of creating a DB view and using that in my model instead?
Upvotes: 1
Views: 298
Reputation: 14874
you can create another property with a different name in another file, extending the main partial class of your model.
EDIT:
namespace YourNameSpace
{
using System.Data.Objects;
public partial class SomeModelEntities
{
public ObjectSet<CampaignType> FilteredCampaignTypes
{
get
{
if ((_CampaignType == null))
{
_CampaignType = base.CreateObjectSet<CampaignType>("CampaignType");
}
return _CampaignType.Where(ct => ct.BusinessArea == BusinessAreas.Outdoor);
}
}
}
}
Upvotes: 1
Reputation: 755
public IQueryable<CampaignType> getCampaignTypes()
{
using (var context = new TestEntities())
{
var campaignTypes = context.CampaignTypes.
Where(ct => ct.BusinessArea == BusinessAreas.Outdoor).
AsQueryable<CampaignTypes>();
return campaignTypes;
}
}
Use the result of this method, instead of accessing context directly. You can also modify your query to return a list, set, etc. by changed the "AsQueryable" method to "AsList", etc.
Upvotes: 0
Reputation: 12596
You can add another layer (a logical layer) between the code that doesn't need to worry about the filter and the entity set. This layer can return an IQuerable or whatever and it would apply the filter to the entity set and return the results.
That way the other parts of your application wouldn't have to worry about applying this filter and it is still a single query (for most cases) that is executing against the database.
Upvotes: 1