开发者

Is using Linq with Stored Procedure perform better than Linq with Generated SQL ?

I do not have a good understandng of how Linq works. I just have tried some examples of L开发者_如何转开发inq that is why I am not sure and have asked the question.

Generally it is said Linq on web is slow. My question is, is Linq with SP give better performance than Linq with Generated SQL ? or both are same.

Please guide.


Because Linq-to-Sql uses a QueryProvider that translates Expressions to SQL statements, it has to do so for every query executed by that provider (unless the query is precompiled [more on that further down]). So, for instance at a basic level:

var people = context.People.Where(p => p.Name == "Matt");

Linq-to-Sql needs to convert the expression p => p.Name == "Matt" into an expression tree, which it in turn converts to a SQL statement, something akin to:

SELECT t0.Name FROM People t0 WHERE t0.Name = 'Matt'

The query when executed against Sql Server, which in turn needs to generate an execution plan for the query and run it against the table to get the results. It's pretty efficient at creating the right query for the right job, and supports more of an ad-hoc approach to data querying.

With stored procedures, Linq-to-Sql doesn't have to generate an expression tree and from that generate the sql, instead the designer generated class has all in information it needs to pass the arguments from the method to the stored procedure.

In that sense, its more efficient to use stored procedures, but you lose the ability to do these ad-hoc queries which are so often useful.

You may find it really comes down to a preference of using sprocs vs. direct queries in your database (discuss this with your DBA).

Compiled queries allow you the benefits of a pre-compiled statement (the query is only generated once), so subsequent queries will use the previously compiled query. An example would be:

public IQueryable<Product> GetProduct(int id)
{
    // Normal query, expression tree and sql generated each time it is
    // it is executed against the data source.
    return context.Products.Where(p => p.Id == id);
}

Whereas a compiled query:

private static readonly Func<DataContext, int, IQueryable<Product>> ProductById = 
    CompiledQuery.Compile((context, id) => 
        context.Products.Where(p => p.Id == id));

public IQueryable<Product> GetProduct(int id)
{
    return ProductById(context, id);
}

The latter will use the precompiled query, so it only generates the expression tree and sql once.


Of course, it all depends on your queries and the amount of data you need to fetch.

The more complex your queries get, the less efficient the SQL generated by LINQ will be.

So in case your queries are very complex/ heavy I'd suggest using stored procedures/ views since then you'll be using the power of the DB server instead of less efficient SQL generated by LINQ2SQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜