简体   繁体   中英

EF and LINQ query to database speed

I just wondering if I am wasting my time or is there anything I could to improve this query which in turn will improve performance.

Inside a Repository, I am trying to get the 10 most recent items

    public List<entity> GetTop10
    {
        get
        {
            return m_Context.entity.Where(x => x.bool == false).OrderByDescending(x => x.Created).Take(10).ToList();
        }
    }

But this is taking a long time as the table its querying has over 11000 rows in it. So my question is, is there anyway I could speed up this kind of query?

I am trying to get my SQL hat on regarding performance, I know the order would slow it down, but how I could I achieve the same result?

Thanks

The particular query you posted is a potential candidate for using a filtered index. Say you have a SQL table:

CREATE TABLE Employees
(
    ID INT IDENTITY(1,1) PRIMARY KEY,
    Name NVARCHAR(100),
    IsAlive BIT
)

You can imagine that generally you only want to query on employees that have not (yet) died so will end up with SQL like this:

SELECT Name FROM Employees WHERE IsAlive = 1

So, why not create a filtered index:

CREATE INDEX IX_Employees_IsAliveTrue 
ON Employees(IsAlive) 
WHERE IsAlive = 1

So now if you query the table it will use this index which may only be a small portion of your table, especially if you've had a recent zombie invasion and 90% of your staff are now the walking dead.

However, an Entity Framework like this:

var nonZombies = from e in db.Employees
                 where e.IsAlive == true
                 select e;

May not be able to use the index (SQL has a problem with filtered indexes and parameterised queries). To get round this, you can create a view in your database:

CREATE VIEW NonZombies
AS
SELECT ID, Name, IsAlive FROM Employees WHERE IsAlive = 1

Now you can add that to your framework (how you do this will vary depending on if you are using code/model/database first) and you will now be able to decide which employees deserve urgent attention (like priority access to food and weapons):

var nonZombies = from e in db.NonZombies
                 select e;

From your LINQ query will be created SQL SELECT similar to this:

SELECT TOP(10) * FROM entity
WHERE bool = 0
ORDER BY Created DESC

Similar because instead of the '*' will server select concrete columns to map these to entity object.

If this is too slow for you. The error is in the database, not in the EntityFramework. So try adding some indexes to your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM