Entity framework 声明变量以存储条件语句的linq实体

Entity framework 声明变量以存储条件语句的linq实体,entity-framework,linq-to-entities,Entity Framework,Linq To Entities,我试图查找记录使用如果我有关键然后使用查找如果没有使用何处 private ApplicationDbContext db = new ApplicationDbContext(); public bool DeactivatePrice(int priceId = 0, string sponsorUserName = "") { var prices = db.BeveragePrices; // if we have an id then

我试图查找记录使用如果我有关键然后使用查找如果没有使用何处

private ApplicationDbContext db = new ApplicationDbContext();

    public bool DeactivatePrice(int priceId = 0, string sponsorUserName = "")
    {
        var prices = db.BeveragePrices;

        // if we have an id then find
        if (priceId != 0)
        {
           prices = prices.Find(priceId);
        }
        else
        {
            prices = prices.Where(b => b.UserCreated == sponsorUserName);
        }

        if (prices != null)
        {
            // do something
        }
        return true;
我得到了以下错误

prices = prices.Find(priceId);
无法从system.data.entity.dbset转换app.Model.BeveragePrices


我正在从中复制模式,但必须有所不同。

似乎您忘记在
Find
函数调用中添加谓词。您还需要对集合执行
ToList
。第二种选择更有效。第一个在选择之前获取整个集合

@Alla评论的另一个注意事项是find返回单个元素。因此,我假设在我在这里陈述的第一个选项中,对“价格”做了另一个声明

price=prices.ToList.Find(b=>b.PriceId==PriceId)

prices=prices.Select(b=>b.PriceId==PriceId)


我假设字段名为PriceId

似乎您忘记在Find函数调用中放置谓词。查看我的答案,了解修复和另一个选项。
Find
方法返回单个实体,但您将
prices
隐式键入为集合。这将导致一个错误。@Alla-我认为您对单个实体的看法是正确的。我会在答案中加上这个。Tnx。