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 ofIQueryable<T>
(where T is type of pen.Type property). This value cannot be converted to integerid
should not be nullable if you are searching by primary key- if
num
is integer, then return type of method should beint
instead ofstring