Custom Criteria objects, Linq and ReadOnlyLists

Custom Criteria objects, Linq and ReadOnlyLists

Old forum URL: forums.lhotka.net/forums/t/5905.aspx


raz0rf1sh posted on Sunday, November 30, 2008

I have a TaskCriteria object that has a property for ProjectId and Status. Sometimes the values are provided, other times they are not. How do I get my DataPortal_Fetch code to handle this using Linq? Here is my current code:


private void DataPortal_Fetch(TaskCriteria criteria)
{
bool cancel = false;
this.OnFetching(ref cancel);
if (cancel)
return;

using (var mgr = ContextManager
.GetManager(Database.ApplicationConnection, false))
{
this.RaiseListChangedEvents = false;
this.IsReadOnly = false;

var data = (from row in mgr.DataContext.Tasks
select TaskInfo.FetchTaskInfo(row));

if (criteria.ProjectId != Guid.Empty)
{
data = (from row in mgr.DataContext.Tasks
where row.ProjectId == criteria.ProjectId
select TaskInfo.FetchTaskInfo(row));
}

//if (criteria.Status != TaskStatus.NotSet)
//{
// data = (from row in mgr.DataContext.Tasks
// where row.Status == (int)criteria.Status
// select TaskInfo.FetchTaskInfo(row));
//}

this.AddRange(data);

this.IsReadOnly = true;
this.RaiseListChangedEvents = true;
}

this.OnFetched();
}

If I uncomment the last section it will only filter by Status, override the ProjectId. How do I make so these Linq statements both work?

Any help would be be much appreciated!

raz0rf1sh replied on Monday, December 01, 2008

Okay ... Got it working ... not sure if this is the right way ... but it works!


private void DataPortal_Fetch(TaskCriteria criteria)
{
bool cancel = false;
this.OnFetching(ref cancel);
if (cancel)
return;

using (var ctx = ContextManager
.GetManager(Database.ApplicationConnection, false))
{
this.RaiseListChangedEvents = false;
this.IsReadOnly = false;

IQueryable query = ctx.DataContext.Tasks;

if (criteria.ProjectId != Guid.Empty)
{
query = query.Where(t => t.ProjectId == criteria.ProjectId);
}

if (criteria.Status != TaskStatus.NotSet)
{
query = query.Where(t => t.Status == (int)criteria.Status);
}

var data = query.Select(t => TaskInfo.FetchTaskInfo(t));

this.AddRange(data);

this.IsReadOnly = true;
this.RaiseListChangedEvents = true;
}

this.OnFetched();
}

JonStonecash replied on Monday, December 01, 2008

I do not know what "right" is in this case, but this is the way that I have done this in the past and it seems to work just fine.  If we are wrong, we are in good company.

Jon Stonecash

raz0rf1sh replied on Monday, December 01, 2008

Thanks Jon! =)

Copyright (c) Marimer LLC