Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this questionLooking to use linq throughout my next project to ease some of the hard labor. Before, I dive into the linq world I would like some advice on best prctices on using linq. I am still undecided on EF and linq to sql
First off, you need to define what you mean by "LINQ". I'm going to guess by the rest of the question that you're asking about Linq to SQL.
If you mean Linq to SQL, and you are starting a new project, I would say that the first Best Practice is to not do it, and use the Entity Framework in .NET. It's far superior to EF 1.0 as well as Linq to SQL. Ever since Visual Studio 2010 and .NET 4 were released, Linq to SQL should be avoided for all new projects.
The biggest Best Practice I can give you is to get the database model right. Properly normalize your database. Properly tune and index your database. Build the EF model off of that properly created database and you will be happy. If you try to cut corners, or you somehow model the database as if it were some sort of non-relational object storage, your life will be one full of pain and suffering.
Make sure everyone on your team understands the concept of deferred execution and how that relates to how your queries are actually generated and executed.
Understand the difference between IQueryable<> and IEnumerable<>. This sort of relates to the previous point, but when it comes to composing Linq queries, understanding how IQueryable<> works can make your life a lot easier.
Understand lazy-loading and how it will affect the performance of your queries. Use it when appropriate, and learn how to eager-load objects strategically for the best performance.
Understand the frequency of each query and what the impact will be on load. Some of your most high-frequency queries can often benefit by being compiled, but most of the time you don't need to do this.
have a look at here 101 LINQ samples http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
Favor casting, instead of parsing for data types.
I found this pretty crucial, as it can drastically improve the readability of your queries.
To avoid being bitten by lazy evaluation, consider this blog post on Best Practices for Linq Enumerables and Queryables by Jon Wagner, which I am quoting here:
- Use “Fluent C#” rather than the language extensions.
- “Seal” LINQ chains as soon as they have been built (if they are going to be reused).
- Only return “open” chains if you want to allow for composition.
- Make sure the semantics for an “open” chain return are clear
- If you are returning an open chain, make sure the inner code is free of side-effects
精彩评论