9

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.

Tnx

4

4 回答 4

7

您可以为您的对象编写扩展;

主要代码;

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

扩大;

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;
        }
于 2010-08-20T07:40:28.153 回答
3

我喜欢搁置使用扩展方法多次使用的大 Select 语句。

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

用法:

 ObjectCtx.SomeEntities.SelectEntityPM();
于 2010-08-20T07:40:29.667 回答
2

一种有用的模式是创建一个可重用的谓词库。查看LINQ PredicateBuilder上的此页面以获取更多信息。

于 2010-08-20T07:43:30.940 回答
2

我经常做的一些事情:

1) 布局:总是在下一行开始查询。示例:不要这样做

var allCustomersThatDontContainUnpayedOrders = from customer in db.Customers
                                               where customer.Orders ...
                                               select customer;

但是这样做:

var allCustomersThatDontContainUnpayedOrders = 
    from customer in db.Customers
    where customer.Orders ...
    select customer;

2) 尽可能使用多个where子句。我试图找到第二个片段比第一个更具可读性:

var results =
    from customer in db.Customers
    where customer.Name.Contains(search) && customer.Address.City != null &&
       customer.Employee.IsSenior
    select customer;

var results =
    from customer in db.Customers
    where customer.Name.Contains(search)
    where customer.Address.City != null
    where customer.Employee.IsSenior
    select customer;

3)如果可以的话,防止加入。LINQ to SQL 通常允许您在所有父子关系上“点”而不使用难以理解的join语句。

4) 通常你会看到很多查询看起来很相似。您可能总是希望根据用户的权限过滤某些记录。您可以在方法中提取此代码:

var customers = db.Customers;

customers = FilterBasedOnUserRights(customers, currentUser);

public static IQueryable<Customer> FilterBasedOnUserRights(
    IQueryable<Customers customers, User currentUser)
{
    return
        from customer in customers
        where [big complicated where clause]
        select customer;
}
于 2010-08-20T08:17:43.383 回答