简体   繁体   中英

LINQ to Entitites: How to take all values by a predicate

I'm trying to get all values that has the same predicate. For example: i have many Packages records that consist of it's own Id, Data and DeviceId which indicates from which device the package has arrived.

Here's the function that I have created which only returns the first package

 public Package GetPackageByDeviceId(int id)
    {
        return avldbContext.Packages.Where(p => p.DeviceId == id).FirstOrDefault();
    }

Any advices on how to get all packages?

public IEnumerable<Package> GetPackagesByDeviceId(int id)
{
    return avldbContext.Packages.Where(p => p.DeviceId == id);
}
public List<Package> PackagesByDeviceId(int id)
{
    return avldbContext.Packages.Where(p => p.DeviceId == id).ToList();
}

First, you need to specify "s" char end of your method. Because the method returns multiple rows. Than without FirstOrDefault(). You need to put a ToList() extension method to pull all records. Good luck.

edit: By the way, your code looks like still looking for primary key. You need to scale your prediction.

If you want to get IEnumerable result

public IEnumerable<Package> GetPackagesByDeviceId(int id)
{
    return avldbContext.Packages.Where(p => p.DeviceId == id);
}

Or if you want to get List

public List<Package> GetPackagesByDeviceId(int id)
{
    return avldbContext.Packages.Where(p => p.DeviceId == id).ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM