A project I\'m working on at the moment involves refactoring a C# Com Object which serves as a database access layer to some Sql 2005 databases.
The author of the existe
I used C# and Linq to do something similar to get log entries filtered on user input (see Conditional Linq Queries):
IQueryable<Log> matches = m_Locator.Logs;
// Users filter
if (usersFilter)
matches = matches.Where(l => l.UserName == comboBoxUsers.Text);
// Severity filter
if (severityFilter)
matches = matches.Where(l => l.Severity == comboBoxSeverity.Text);
Logs = (from log in matches
orderby log.EventTime descending
select log).ToList();
Edit: The query isn't performed until .ToList() in the last statement.
This is the way I'd do it:
public IQueryable<ClientEntity> GetClients(Expression<Func<ClientModel, bool>> criteria)
{
return (
from model in Context.Client.AsExpandable()
where criteria.Invoke(model)
select new Ibfx.AppServer.Imsdb.Entities.Client.ClientEntity()
{
Id = model.Id,
ClientNumber = model.ClientNumber,
NameFirst = model.NameFirst,
//more propertie here
}
);
}
The Expression parameter you pass in will be the dynamic query you'll build with the different WHERE clauses, JOINS, etc. This Expression will get Invoked at run time and give you what you need.
Here's a sample of how to call it:
public IQueryable<ClientEntity> GetClientsWithWebAccountId(int webAccountId)
{
var criteria = PredicateBuilder.True<ClientModel>();
criteria = criteria.And(c => c.ClientWebAccount.WebAccountId.Equals(webAccountId));
return GetClients(criteria);
}
I understand the potential of Linq but I have yet to see anyone try and do a Linq query of the complexity that Ben is suggesting
the fairly complex sql statement (~10 joins, >10 sub selects, ~15-25 where conditions and GroupBy's)
Does anyone have examples of large Linq queries, and any commentary on their manageability?
If using C# and .NET 3.5, with the addition of MS SQL Server then LINQ to SQL is definitely the way to go. If you are using anything other than that combination, I'd recommend an ORM route, such as nHibernate or Subsonic.
You may want to consider LINQ or an O/R Mapper like this one: http://www.llblgen.com/
Check out http://sqlom.sourceforge.net. I think it does exactly what you are looking for.