Question

I was trying to return a column value in a table called with its ID .

    public String PenTypes(int?id, Pen pen)
    {
    int num;

      var query = from d in db.Pens
                   where d.ID == 1
                   select d.Type;

      num=Convert.ToInt(query);
      return num;

I have no clue as to where i'm going wrong. I do know its simple, but I'm really new to using Entity Framework. Any Help would be appreciated.

Was it helpful?

Solution

I suggest you to use DbSet<TEntity>.Find method if you want to get entity by id:

  var pen = db.Pens.Find(id);
  if (pen == null)
     // handle case when pen is not found

  return pen.Type; // if type is string, then you possibly need to parse it

Or you can use FirstOrDefault/SingleOrDefault:

  var pen = db.Pens.FirstOrDefault(p => p.ID == id);

Your current code has several problems:

  • query will have type of IQueryable<T> (where T is type of pen.Type property). This value cannot be converted to integer
  • id should not be nullable if you are searching by primary key
  • if num is integer, then return type of method should be int instead of string
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top