0

I am trying to look up record using if I have the key then use Find if not use 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;

I get the following error for

prices = prices.Find(priceId);

Cannot convert app.Model.BeveragePrices from system.data.entity.dbset

I am copying the pattern from this answer but something must be different.

3
  • Seems you forgot to put a predicate inside the Find function call. See my answer for a fix and another option. Commented Oct 19, 2014 at 19:07
  • 1
    The Find method returns a single entity but you have prices implicitly typed as a collection. This will cause an error. Commented Oct 19, 2014 at 22:22
  • @Alla - I think you are right about the single entity. I'll add this to the answer. Tnx. Commented Oct 22, 2014 at 1:49

1 Answer 1

1

Seems you forgot to put a predicate inside the Find function call. Also you need to do ToList on the collection. The second option is a lot more efficient. The first one gets the whole collection before selection.

Another note commented by @Alla is that the find returns a single element. So I assume another declaration had been made for 'price' in the first option I state down here.

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

Or

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

I assume the field name is PriceId.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.