czWolfHunter
czWolfHunter

Reputation: 397

Linq to SQL - how to make a select with conditions and return IQueryable

I can not find answers how to implement the following scenario (I do not know what to look for methods). I use C#, .NET FW4.5, Linq to SQL and design pattern repository.

If I want to select all devices, use this code:

/// <summary>
/// Get all Devices
/// </summary>
/// <returns></returns>
public IQueryable<Device> GetDevices()
{
    return myDataContext.Devices;
}

If I want to select device by ID, use this code:

/// <summary>
/// Get Device by ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public Device GetDevice(int id)
{
    return myDataContext.Devices.SingleOrDefault(
        d => d.intDeviceId == id);
}

But how can I implement the following situation?

Select all devices, where are some conditions (and return IQueryable<Device>)

Upvotes: 0

Views: 1036

Answers (2)

Flowerking
Flowerking

Reputation: 2581

You can use it like :

public IQueryable<Device> GetDeviceUsingPredicate(Expression<Func<Device,bool>> predicate)
{
    return myDataContext.Devices.Where(predicate).AsQueryable();
}

To use with generics:

public IQueryable<T> GetDeviceUsingPredicate(Expression<Func<T,bool>> predicate)
{
    return myDataContext.GetTable<T>().Where(predicate).AsQueryable();
}

Upvotes: 2

xlecoustillier
xlecoustillier

Reputation: 16351

Try:

return myDataContext.Devices.Where(
        d => yourConditions).AsQueryable();

Upvotes: 3

Related Questions