user892239
user892239

Reputation: 149

Cannot see FirstOrDefault

Any Help is much appreciated guys!

under GetProductByID, i am getting an error saying "int does not contain a definition for FirstOrDefault".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HomebaseSystemNew.Models;

namespace HomebaseSystemNew.Controllers
  {
    public class ProductRepository
   {

    public ProductsController GetProductID(int Pid)
        {
          Product db = new Product();

          return db.Pid.FirstOrDefault(db => db.Pid == Pid);
        }


   }




   }

Upvotes: 10

Views: 19074

Answers (5)

maxspan
maxspan

Reputation: 14147

Also You need to add using System.Linq namespace to access those methods.

Upvotes: 33

ipr101
ipr101

Reputation: 24236

FirstOrDefault is an extension method on an IEnumerbale or IQueryable, you're trying to call it from an integer.

Upvotes: 0

ChrisF
ChrisF

Reputation: 137128

Well int doesn't contain a definition for FirstOrDefault because it's not a list type.

You'll need a list of ints for this to work:

public ProductsController GetProductID(List<int> Pids)
{
    ....
}

or more likely

public ProductsController GetProductID(int Pid)
{
    Product db = new Product();

    return db.Products.FirstOrDefault(db => db.Pid == Pid);
}

assuming you have a table called Product in your database.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500245

It sounds very unlikely that you want to start with a Product instance. The correct code is more likely to look like:

public Product GetProductByID(int id)
{
    return new DbContext().Products
                          .FirstOrDefault(p => p.Pid == id);
}

After all, you don't logically get from a single product to a collection of products, let alone from a single product ID to a collection of . You haven't said where your data is or anything like that, but you need to be applying FirstOrDefault to a collection of products.

Upvotes: 3

Oded
Oded

Reputation: 498972

From your code it appears that db.Pid is an integer (Int32), not an IEnumerable<T>.

The LINQ operators are defined on IEnumerable, not Int32.

By default it will be 0.

Upvotes: 0

Related Questions