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

时间:2014-10-19 18:33:26

标签: entity-framework linq-to-entities

我正在尝试查找记录,如果我有密钥然后使用查找,如果不使用Where

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

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

1 个答案:

答案 0 :(得分:1)

似乎你忘了在Find函数调用中放置一个谓词。您还需要对集合执行ToList。第二种选择更有效率。第一个在选择之前获得整个集合。

@Alla评论的另一个注释是find返回一个元素。所以我假设已经为“价格”做了另一个声明。在第一个选项中,我在这里说明。

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

或者

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

我认为字段名称是 PriceId