简体   繁体   English

LINQ 到实体:如何通过谓词获取所有值

[英]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.例如:我有许多包记录,其中包含它自己的 Id、Data 和 DeviceId,这表明 package 来自哪个设备。

Here's the function that I have created which only returns the first package这是我创建的 function,它只返回第一个 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.首先,您需要指定方法的“s”字符结尾。 Because the method returns multiple rows.因为该方法返回多行。 Than without FirstOrDefault().比没有 FirstOrDefault()。 You need to put a ToList() extension method to pull all records.您需要放置一个 ToList() 扩展方法来提取所有记录。 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如果你想得到IEnumerable结果

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

Or if you want to get List或者,如果您想获取List

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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