Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7866595
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T00:26:44+00:00 2026-06-03T00:26:44+00:00

We are using EF 4.3 for our data layer and have a generic repository

  • 0

We are using EF 4.3 for our data layer and have a generic repository pattern in place. Backend is SQL 2008 R2 and the project is .NET 4.0/MVC 3 but I don’t think that this factors into the question.

Basically, we have a one to many relationship in our database of two objects. One is for ‘Traps’ and the second is for ‘Trap Activities’. Meaning, once one of these ‘Traps’ is deployed, anything that happens to that trap is kept in the Trap Activity table. Should be a fairly straightforward way of doing this.

The relationship is defined with a FK in the ‘Trap Activity’ table to the PK of the ‘Traps’ table. Both tables have PKs defined.

In our service layer, I need to query out a list of ‘Traps’ with the date that these traps were deployed. This is accomplished by the following code snippet:

var traps = this.trapRepository.Find(x => x.DeploymentYear == 2012).Select(x => new TrapHomeViewModel
            {
                County = x.County.Name,
                DeploymentDate = x.TrapActivities.First(y => y.ActivityType == 1).ActivityDate,
                State = x.County.CountyState.Abbreviation,
                Latitude = x.Latitude,
                Longitude = x.Longitude,
                TrapId = x.TrapID,
                TrapNumber = x.SerialNumber,
                Centroid = x.TrapCentroid
            }).ToList();

The issue is around the DeploymentDate property. As written, this takes 25s to return a list of around 3000 items. Updating the Trap table to have the deployment date to be stored there and populating with this line:

DeploymentDate = x.DeploymentDate.Value.Date

Results in a less than 1s response time. Now I think I know what is going on here (multiple enumerations of the data set) but what I thought would happen would be a query similar to the following:

SELECT     Counties.Name, TrapActivities.ActivityDate, States.Abbreviation, 
Traps.Latitude, Traps.Longitude, Traps.TrapID, Traps.SerialNumber, Traps.TrapCentroid
    FROM         TrapActivities INNER JOIN
                          Traps ON TrapActivities.TrapID = Traps.TrapID INNER JOIN
                          Counties ON Traps.CountyID = Counties.CountyID INNER JOIN
                          States ON Counties.State = States.FIPS_Code
    WHERE     (TrapActivities.ActivityType = 1)

…but that does not seem to be the case. With all the background information above, where have I strayed in populating this view model? I don’t think I have ran into this issue before but this is also a much larger dataset than some of our other projects. Any guidance on this would be much helpful. If I need to provide any other information, please let me know.

EDIT

As requested, the GenericRepository Find method and constructors:

 public class GenericRepository<T> : IGenericRepository<T>
        where T : class
    {
        private readonly IObjectSet<T> objectSet;
        private ObjectContext context;

        public GenericRepository()
            : this(new APHISEntities())
        {
        }

        public GenericRepository(ObjectContext context)
        {
            this.context = context;
            this.objectSet = this.context.CreateObjectSet<T>();
        }    

        public IEnumerable<T> Find(Func<T, bool> predicate)
        {
            return this.objectSet.Where(predicate);
        }

EDIT 2

This is an example of the SQL being generated by the above code:

exec sp_executesql N'SELECT 
[Extent1].[TrapActivityID] AS [TrapActivityID], 
[Extent1].[TrapID] AS [TrapID], 
[Extent1].[ActivityType] AS [ActivityType], 
[Extent1].[Notes] AS [Notes], 
[Extent1].[AgentID] AS [AgentID], 
[Extent1].[ActivityDate] AS [ActivityDate], 
[Extent1].[CreatedOn] AS [CreatedOn], 
[Extent1].[EditedOn] AS [EditedOn], 
[Extent1].[Deleted] AS [Deleted], 
[Extent1].[VisualInspectionID] AS [VisualInspectionID]
FROM [dbo].[TrapActivities] AS [Extent1]
WHERE [Extent1].[TrapID] = @EntityKeyValue1',N'@EntityKeyValue1 uniqueidentifier',@EntityKeyValue1='FEBC7ED4-E726-4F5E-B2BA-FFD53AB7DF34'

It looks to me that it is taking a list of Trap Ids and then running a query for each one, resulting in thousands of SQL statements being generated. It also appears to be running individual queries for the County information as well.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T00:26:46+00:00Added an answer on June 3, 2026 at 12:26 am

    In your repository, you can use ObjectQuery.ToTraceString to see what SQL is getting executed before you return your objects.

    You are returning all of the actual Trap objects deployed in 2012 from your repository find method, instead of an IQueryable AND you are not eager loading TrapActivities. That means as you enumerate through the results in Select to create your view model, you are sending a new query to the DB for each Trap to get it’s TrapActivities.

    Update 1

    I think you will need to implement a specific query in your repository for this.

    var q = from t in traps 
            where t.DeploymentYear == 2012
            select new TrapFirstDeployment {
                Trap = t,
                DeploymentActivity = t.TrapActivities.Where(ta=>ta.FirstOrDefault(a=>a.ActivityType=1))
            };
    
    return q.Where(tfd=>tfd.DeploymentActivity != null);
    

    Explanation

    The reason your initial query was slow is because EF doesn’t eager load child relationships unless you tell it to. Lazy Loading is on by default. Since you don’t tell it to load TrapActivities with your Trap in your repository, it waits until you access it the first time to load them. This is great you need the trap but not the activities because it reduces traffic to/from the DB. However, in some situations you need them. In that case you can force an eager load by adding Include in your query. e.g.,

    var q = from t in this.objectSet.Include('TrapActivities')
            select t;
    

    This loads ALL of the TrapActivities with the trap in one query. However, in your case, you only need the first deployment activity which is why I created the TrapFirstDeployment class. This way, EF should only grab the first deployment activity.

    Update 2

    You should also change the parameter on the Find method on your repository to Expression<Func<T,Boolean>> to match the IQueryable.Where signature. IEnumerable.Where uses Func<T,Boolean> so that is why objectSet is getting converted to an IEnumberable before Where is called.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

in our current project we are using ADO.NET Entity Framework as data layer for
Our ASP.NET MVC project uses MS SQL Server (for most of the data) and
We are using Nhibernate as our data access layer. We have a table of
I have an existing complex website built using ASP.NET MVC, including a database backend,
I have an existing ASP.Net MVC project that is using entities / repositories in
I have implemented the repository pattern using the following generic interface. public interface IRepository<T>
I have a project with a formidable data access layer using LinqtoSQL for just
Last year I developed a data access service for our project using Entity Framework
I have a data mart mastered from our OLTP Oracle database using basic Materialized
Our current web application is using SQL Server, we have a requirement for support

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.