Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design of LINQ code

Tags:

c#

.net

linq

What are your suggestions for designing linq code in project? Especially, I`m interesting in code design of big and complex linq queries?

For example, you know, that you need to write a lot of huge linq stuff, maybe some of your code will have duplicate parts, maybe not, and you need:

  1. Make the code easily supportive - means, if you need to change something . - you are changing one thing, not many

  2. Make the code easy to read - means, if you need to find something - you easily doing this.

You can use your examples, maybe your practice. Maybe some patterns, that you saw anywhere - anything.

Saying linq I mean any linq, linq to sql, linq to objects, linq to xml, etc.

like image 949
Archeg Avatar asked Aug 20 '10 07:08

Archeg


People also ask

What is LINQ syntax?

LINQ query syntax is consist of a set of query keywords defined into the . NET Framework version 3.5 or Higher. This allows the programmer or developers to write the commands similar to SQL style in the code(C# or VB.NET) without using quotes. It is also know as the Query Expression Syntax.

What is LINQ example?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


2 Answers

you can write extensions for your objects;

Main code;

IQuerable itemList = _coreRepository.GetSomeItems()
                .WithStates(OperationIdentity.SendToSomeWhere)
                .BetweenDates(StartDate, EndDate);

Extension;

public static IQueryable<SomeObject> BetweenDates(this IQueryable<SomeObject> query, DateTime startDate, DateTime endDate)
        {
            return from p in query
                   where p.CompletedDate >= startDate && p.CompletedDate < endDate
                   select p;
        }
like image 100
NetSide Avatar answered Oct 04 '22 14:10

NetSide


I like to put aside big Select statements that are used many times using extension methods.

public static IQueryable<SomeEntityPM> SelectEntityPM(this IQueryable<SomeEntity> entities)
{
     return entities.Select(a => new SomeEntityPM { ... });
}

Usage:

 ObjectCtx.SomeEntities.SelectEntityPM();
like image 45
Stephane Avatar answered Oct 04 '22 14:10

Stephane